//Stores the refrence to the xmlHTTPRequest Object
var xmlHttp = createXmlHttpRequestObject();


function eventRecordDelete(id){
	//cccalert(id);
	r=confirm('Are you sure you want to delete this event?');
	if(r==true){
		$.post('delete1.php',{'id':id},function(data){
			alert('Event Deleted Successfully');
			location.reload();
		});
	}
}


//retrieves the xmlHttpRequest Object
function createXmlHttpRequestObject()
{
	//will store the refrence to the xmlHttpRequest Object
	var xmlHttp;
	//if running in internet explorer version below 7
	if(window.ActiveXObject)
	{
			try{
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(e){
				xmlHttp = false;
			}
	}
	else
	{
		try{
			xmlHttp = new XMLHttpRequest();
		}
		catch(e){
			xmlHttp = false;
		}
	}
	if(!xmlHttp)
		alert("Error Creating the xmlHttpObject");		
	else
		return xmlHttp;
}

//-------------------------------------------Library
//****************************************************
function $V(fieldId)
{
	return document.getElementById(fieldId).value;
}

function $F(fieldId)
{
	return document.getElementById(fieldId).focus();
}

function $HTML(fieldId)
{
	return document.getElementById(fieldId).innerHTML;	
}

function $Id(fieldId)
{
	return document.getElementById(fieldId);
}

//-------------------------------------------Encode in Base64
//****************************************************
function make_base_auth(user, pass) 
{
	var tok = user + ':' + pass;
	var hash = Base64.encode(tok);
	//var hash = encodeURIComponent(tok);
	return "Basic " + hash;
}

//------------------------------Function for Validation Only
//****************************************************
function checkLoginInfo()
{
	if($V('grupioUser') == '')
	{
		showDialog('Warning','You must enter the Name of the user.','warning',4);
		setTimeout( function()
					{
						$F('grupioUser');				
					},4000);
		
		return false;
	}
	if($V('grupioPassword') == '')
	{
		showDialog('Warning','You must enter the Password.','warning',4);
		setTimeout( function()
					{
						$F('grupioPassword');				
					},3000);
		return false;
	}
	checkUserExistsInDatabase();
}


function checkUserExistsInDatabase()
{
	if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
	{
		//var organizationId = encodeURIComponent($V('organization_id'));
		//UserId for HTTP-Authentication
		var userIdForHTTPAuthentication 	= $V('grupioUser');

		//Password for HTTP-Authentication
		var passwordForHTTPAuthentication 	= $V('grupioPassword');

		//keep_login for HTTP-Authentication
		var login_keep 						= $V('login_keep');

			var queryString = 'operation=login&userid=' + userIdForHTTPAuthentication + '&password=' + passwordForHTTPAuthentication + '&login_keep=' + login_keep;
               
			var url = "adminlogin.php";
			
			xmlHttp.open("POST", url, true);
			
			//Send the proper header information along with the request
			xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlHttp.setRequestHeader("Content-length", queryString.length);
			xmlHttp.setRequestHeader("Connection", "close");
			
			xmlHttp.onreadystatechange = checkHandleServerResponse;			
			xmlHttp.send(queryString);	
	}
}


function checkHandleServerResponse()
{
	if(xmlHttp.readyState == 4)
	{
		if(xmlHttp.status == 200)
		{
			var JSONFile = 'jsonFormatData = '+ xmlHttp.responseText;
			eval(JSONFile);
			if(jsonFormatData.description == 'Success')
			{
				//showDialog('Success','Login Successful','success',3);
				location.href='myGrupio.php';	
				//setTimeout(function(){location.href='myGrupio.php';},3000);
			}
			else
				showDialog('Error','You Need a Valid Login.','error',3);
		}
		else if(xmlHttp.status == 400)
		{
			showDialog('Error','You Need a Valid Login.','error',3);
			setTimeout( function()
						{
							$Id('grupioPassword').value = '';
							$F('grupioUser');
						},3000);
		}
		else 
			alert("Error Code is "+xmlHttp.status)
	}
}


function sessionLogOut()
{
	if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
	{
			var queryString = 'operation=logout';

			var url = "adminlogin.php";
			xmlHttp.open("POST", url, true);
			
			//Send the proper header information along with the request
			//xmlHttp.setRequestHeader('Authorization', httpAuthentication);
			
			xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlHttp.setRequestHeader("Content-length", queryString.length);
			xmlHttp.setRequestHeader("Connection", "close");
			
			xmlHttp.onreadystatechange = sessionLogOutHandleServerResponse;			
			xmlHttp.send(queryString);	
	}
	else
		setTimeout(function(){sessionLogOut();}, 1000);
}


function sessionLogOutHandleServerResponse()
{
	if(xmlHttp.readyState == 4)
	{
		if(xmlHttp.status == 200)
		{
			var JSONFile = 'jsonFormatData = '+xmlHttp.responseText;
			eval(JSONFile);
			if(jsonFormatData.description == 'Success')
			{
					//showDialog('Success','Successfully Logut','success', 4);
					location.href='index.php';
					//setTimeout(function(){location.href='index3.php';}, 3000);
			}
		}
	}
}


function fillGrupioTable(userid , password, organizationID)
{
	if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
	{
		//UserId for HTTP-Authentication
		var userIdForHTTPAuthentication = userid;
		//Password for HTTP-Authentication
		var passwordForHTTPAuthentication = password;
		
		var httpAuthentication = make_base_auth(userIdForHTTPAuthentication, passwordForHTTPAuthentication);
// 		rommy - make the organizationID as dymanic
//		var queryString = 'organization_id=1&event_id=&name=&start_date=&object_type=event&operation=show';
		if(organizationID == '' || organizationID == 0) organizationID = 1;
		var queryString = 'organization_id='+organizationID+'&event_id=&name=&start_date=&object_type=event&operation=show';
	
			var url = "do.php";
			xmlHttp.open("POST", url, true);

			//Send the proper header information along with the request
			xmlHttp.setRequestHeader('Authorization', httpAuthentication);
			
			xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlHttp.setRequestHeader("Content-length", queryString.length);
			xmlHttp.setRequestHeader("Connection", "close");
			
			xmlHttp.onreadystatechange = fillGrupioTableHandleServerResponse;			
			xmlHttp.send(queryString);	
	}
	else
		setTimeout(function(){fillGrupioTable(userid , password)},1000);
}


function fillGrupioTableHandleServerResponse()
{
	if(xmlHttp.readyState == 4)
	{
		if(xmlHttp.status == 200)
		{
			
				var JSONFile = 'jsonFormatData = '+xmlHttp.responseText;

				eval(JSONFile);
				var tableId = $Id('eventTable');
				totalNoRows = jsonFormatData.length;
				if(totalNoRows != 0)
					$Id('eventTableDiv').style.display = 'block';
				
				var eventTableHTML = '';
				for(i=0;i<totalNoRows;i++)
				{
					eventID = parseInt(jsonFormatData[i]['event_id']);
					
					editCellInnerHTML = '<form action="myGrupio.php" method="post" id="form'+eventID+'" name="form'+eventID+'">';
					editCellInnerHTML += '<input type="hidden" name="event_id" value="'+eventID+'" />';
					editCellInnerHTML += '<input type="hidden" name="httpAuthenticateUser" id="httpAuthenticateUser" value="' + userid +'" />';
					editCellInnerHTML += '<input type="hidden" name="httpAuthenticatePassword" id="httpAuthenticatePassword" value="' + password + '" />';
					editCellInnerHTML += '<input type="image" src="images/edit.png" title="Edit" alt="Edit" /></form>';
					editCellInnerHTML  += '<td class="tdcolor" align="center"><a href="#" onclick="eventRecordDelete('+eventID+');">';
					editCellInnerHTML  += '<img src="images/delete.png" alt="Delete" title="Delete" /></a></td>';
					
					eventTableHTML += '<tr id="'+ i +'_sponsor_tr">';
					eventTableHTML += '<td class="tdcolor" align="center">';
					eventTableHTML += editCellInnerHTML + '</td>';
					eventTableHTML += '<td class="tdcolor" align="center">' + jsonFormatData[i]['name'] +'</td>';
					eventTableHTML += '<td class="tdcolor" align="center">' + jsonFormatData[i]['start_date'] + '</td>';
					eventTableHTML += '<td class="tdcolor" align="center">' + jsonFormatData[i]['end_date'] +'</td>';
					//eventTableHTML += '<td class="tdcolor" align="center"><p>' + wordwrap(jsonFormatData[i]['description'],50,'<br />\n',true) + '</p></td>';
					eventTableHTML += '<td class="tdcolor" align="center"><p>' + jsonFormatData[i]['description'] + '</p></td>';
//					eventTableHTML += '<td class="tdcolor" align="center">' + wordwrap(jsonFormatData[i]['image'],50,'<br />', true) + '</td>';
					eventTableHTML += '<td class="tdcolor" align="center">' + jsonFormatData[i]['image'] + '</td>';
					eventTableHTML += '<td class="tdcolor" align="center">' + jsonFormatData[i]['address1'] + ' , ' + jsonFormatData[i]['address2']; + '</td>';
					eventTableHTML += '<td class="tdcolor" align="center">' + jsonFormatData[i]['city'] + '</td>';
					eventTableHTML += '<td class="tdcolor" align="center">' + jsonFormatData[i]['state'] + '</td>';
					eventTableHTML += '<td class="tdcolor" align="center">' + jsonFormatData[i]['country'] + '</td>';
					eventTableHTML += '<td class="tdcolor" align="center">' + jsonFormatData[i]['zipcode'] + '</td></tr>';					

				}
				if(eventTableHTML != '') {
					$('#eventTable').append(eventTableHTML);
				}

				//--- Below snippet are for 'Read more...' functionality
				$('td.tdcolor p').expander({
					slicePoint:       80,  // default is 100
					expandText:         'read more', // default is 'read more...'
					collapseTimer:    5000, // re-collapses after 5 seconds; default is 0, so no re-collapsing
					userCollapseText: '[hide]'  // default is '[collapse expanded text]'
				});	
				//----Ends here
				addNewEventInnerHTML = '<form action="myGrupio.php" method="post" style="float:left;">';
				//addNewEventInnerHTML += '<input type="hidden" name="event_id" value="'+eventID+'" />';
				addNewEventInnerHTML += '<input type="hidden" name="httpAuthenticateUser" id="httpAuthenticateUser" value="' + userid + '" />';
				addNewEventInnerHTML += '<input type="hidden" name="httpAuthenticatePassword" id="httpAuthenticatePassword" value="' + password + '" />';
				addNewEventInnerHTML += '<input type="submit" value="Add New Event" class="button button_blue" /></form>';
				addNewEventInnerHTML += '&nbsp;<input type="button" value="Excel Upload" class="button button_blue" onclick="javascript: window.location.href=\'myGrupio.php?action=upload\'" />';
								
				$Id('addNewEvent').innerHTML = addNewEventInnerHTML;
		}
	}
}
