var currentDate = 0;
var CHECK_MARK ="&#x2713;";
var allClusters;
window.onload = function() {
	//console.log("window loading...");
  updateDayAndTime(new Date(),true);
  getFriendsAndContacts();
  
  Event.observe(document.body, 'onMouseOver', function(event) {
	  var element = Event.element(event);
	
	  if ('table' == element.tagName)
	    element.hide();
	});
  
 
};

function clearText(field){

    if (field.defaultValue == field.value) field.value = '';
    else if (field.value == '') field.value = field.defaultValue;

}

 
 function ajaxRequest(url,data){
	   var myAjax = new Ajax.Request(url, {method: 'get', parameters: data, onComplete: getResponse});
}
 
 function getResponse(oReq, oJSN) {
	var data = eval(oReq.responseText);
	//$('test-div').innerHTML = '';
}

 
 function getResponse(oReq) {  
	   
	 var eventOrContact = document.getElementById('event_or_contact').value;
	
	 
	 if(eventOrContact == 'addevent') {
		 document.getElementById('event_or_contact').value = 'addcontact';
		 $('mod_quick_add_event').clear();
		 $('mod_quick_add_event').focus();
		 $('result').innerHTML = oReq.responseText;
	 }
	 else if(eventOrContact == 'addcontact') {
		 $('mod_quick_add_contact').clear();
		// $('contacts_count').update();
		
		 $('contacts_count').update(oReq.responseText);
	//	 $('contacts_count').innerHTML = oReq.responseText;
	   $('mod_quick_add_contact').focus();
	 }
	 else {// came from event
		 $('mod_quick_add_contact').clear();
	//	 $('contacts_count').innerHTML = oReq.responseText;
		// $('contacts_count').update();
		 $('contacts_count').innerHTML = oReq.responseText;
		// $('contacts_count').update(oReq.responseText);
		 document.getElementById('event_or_contact').value = 'addcontact';//set hidden field value to old
		
		
		 $('mod_quick_add_event').focus();
	 }

 }
 
 function updateSpanWithValue(value){
	 var SPAN = document.getElementById('contacts_count');
	 var text = document.createTextNode(value);
	 if(SPAN.childNodes.length == 0){
	 SPAN.appendChild(text)
	 }
	 else
	 {
	 SPAN.firstChild.nodeValue = value;
	 }
	 }
 
function echeck(str) {
	  var at="@";
	  var dot=".";
	  var lat=str.indexOf(at);
	  var lstr=str.length;
	  var ldot=str.indexOf(dot);
	  if (str.indexOf(at)==-1){
	     return false;
	  }
	  
	  if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	     return false;
	  }
	  
	  if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
	      return false;
	  }
	  
	   if (str.indexOf(at,(lat+1))!=-1){
	      return false;
	   }
	  
	   if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
	      return false;
	   }
	  
	   if (str.indexOf(dot,(lat+2))==-1){
	      return false;
	   }
	  
	   if (str.indexOf(" ")!=-1){
	      return false;
	   }
	  
	    return true;
	}


function setInfoAddEvent() {
	 document.getElementById('event_or_contact').value = 'addevent';
}

function getFocusOnContactField() {
	 document.getElementById('event_or_contact').value = 'addcontactWithResponse';

	document.getElementById('mod_quick_add_contact').focus();
}

function validateContactEmail() {
	  if(document.globalAddContact.contact_email.value.trim()=="") {
	    alert("Please insert an e-mail");
	    document.globalAddContact.contact_email.focus();
	    return false;
	  }
	  if(!echeck(document.globalAddContact.contact_email.value)) {
	    alert("Please insert a valid e-mail address");
	    document.globalAddContact.contact_email.focus();
	    return false;
	  }
	  return true;
	}

function validateEvent() {
	  if(document.globalAddEvent.title.value.trim()=="") {
	    alert("Event name cannot be empty");
	    document.globalAddEvent.title.focus();
	    return false;
	  }
	  return true;
	}

function serializeForm(form) {
	    return $(form).getInputs('text').invoke('serialize').join('&');
 }

function former(data, test) {
	var contacthack = "";
}

function updateDayAndTime(currentDate,increase) {
	var now = new Date();
	var currentHour = currentDate.getHours();
	var currentMinutes = currentDate.getMinutes();
	var hourString = "";
	var hoursToAdd = 0;
	
	if(increase == true) {
		if(currentMinutes >= 0 && currentMinutes <=30) {
			currentHour = currentHour + 1;
			hoursToAdd = 1;
		}
		else {
			currentHour = currentHour + 2;
			hoursToAdd = 2;
		}
	}
	
	if(increase == true) {
		if(currentHour >= 24) {
			currentHour = currentHour - 24;
				document.getElementById('ftl_calendar2').innerHTML= "Tomorrow";		
		}
		else
			document.getElementById('ftl_calendar2').innerHTML= "Today";
	}
	else {
		var day  =  now.getDate();
		var currentday = currentDate.getDate();
		var diff = currentday - day;
		if(now.getDate() == currentDate.getDate() && now.getMonth() == currentDate.getMonth() && now.getYear() == currentDate.getYear())
			document.getElementById('ftl_calendar2').innerHTML= "Today";
		else if(diff > 0 && diff <= 1 && now.getMonth() == currentDate.getMonth() && now.getYear() == currentDate.getYear())
			document.getElementById('ftl_calendar2').innerHTML= "Tomorrow";
		else if(diff < 0 && diff >= -1 && now.getMonth() == currentDate.getMonth() && now.getYear() == currentDate.getYear())
			document.getElementById('ftl_calendar2').innerHTML= "Yesterday";
		else {
			document.getElementById('ftl_calendar2').innerHTML = currentDate.toDateString();
		}
		
	}
	
	var dateToMilli = currentDate.getTime();
	
	if(increase == true)
		dateToMilli = dateToMilli - (currentDate.getMinutes() * 1000 * 60) + (hoursToAdd * 1000 * 60 * 60);
	
	if(currentHour >= 12) {
		if(currentHour == 12)
			hourString = "12 pm";
		else
			hourString = ((currentHour - 12) + '') + " pm";
	}
	else 
		hourString = (currentHour  + '') + " am";

	 $('mod_qae_time').innerHTML = hourString;
	 document.getElementById('mod_qae_date').value = dateToMilli;
	 currentDate = dateToMilli;
}

function increaseTime(by) {
	var currentMill = parseInt(document.getElementById('mod_qae_date').value);
	var mill = currentMill + (1000 * 60 * 60 * by);
	updateDayAndTime(new Date(currentMill + (1000 * 60 * 60 * by)),false);
}

function getCurrentDate() {
	return parseInt(document.getElementById('mod_qae_date').value);
}

function toggle_visibility(id) {
    var divTag = document.getElementById(id);
    if(divTag.style.display == 'none') {
    	//divTag.style.display = 'none';
    	var divTag = document.getElementById(id);
        var iFrameTag = document.getElementById("selectblocker");
        var tableTag = document.getElementById("contents");
        var AnchorPos = getAnchorPosition("jds_count")
        divTag.style.left=AnchorPos.x+20;
        divTag.style.top=AnchorPos.y+22;
        divTag.style.width=300;
        divTag.style.height=150;
        iFrameTag.style.left = 0;
        iFrameTag.style.top = 0;
        iFrameTag.style.width = divTag.style.width;
        iFrameTag.style.height = divTag.style.height;
        iFrameTag.style.zIndex = divTag.style.zIndex-1;

        tableTag.style.left = 0;
        tableTag.style.top = 0;
        tableTag.style.width = divTag.style.width;
        tableTag.style.height = divTag.style.height;
        tableTag.style.zIndex = divTag.style.zIndex;
        divTag.style.display = "block";
       
    }
    else {
    	divTag.style.display = 'none';
    	
    }
 }

function createNoFriendsTable(name) {
	var tbodyElem = document.getElementById(id);
	var trElem, tdElem;
	trElem = tbodyElem.insertRow(tbodyElem.rows.length);
	   // first column
	   tdElem = trElem.insertCell(trElem.cells.length); 
	   tdElem.innerHTML =   name;
}

function populateTable(id,tableData) {
	
	if(tableData.length == 0) {
	
		createNoFriendsTable("You have no friends");
		return;
	}
	
	var tbodyElem = document.getElementById(id);
	var trElem, tdElem;
	var clusterid = 0;
	var selectedClusters = "";
	
	var CHECK_MARK ="&#x2713;";
	
	for (var i in tableData) {
		for (var j in tableData[i]) //for each key in row entries e.g j = clusterid, count tableData[i][j] = cluserid value, count value
		
		   trElem = tbodyElem.insertRow(tbodyElem.rows.length);
		   // first column
		   tdElem = trElem.insertCell(trElem.cells.length); 
		   tdElem.innerHTML =   CHECK_MARK;
		   tdElem1 = trElem.insertCell(trElem.cells.length); 
		   tdElem1.innerHTML =    i;
		   
		   for (var j in tableData[i]) {
			   tdElem1 = trElem.insertCell(trElem.cells.length); 
			   //tdElem1.innerHTML =    i;
			   if(j == "clusterid") {
				   clusterid = tableData[i][j];
				   selectedClusters += "|" + tableData[i][j];
			   }
			   else  if(j == "count")  {
				   if(i == "All Connections")
					   document.getElementById('jds_count').innerHTML = tableData[i][j];
				
			   }
			 //  console.log("i:" + i + " j::" + j + " (i,j)::" + tableData[i][j]);
			   var input = document.createElement("input");
			   input.setAttribute("type", "hidden");
			   input.setAttribute("name", "c" + clusterid + "_" + j);
			   input.setAttribute("id", "c" + clusterid + "_" + j);
			   input.setAttribute("value", tableData[i][j]);
			   tdElem1.appendChild(input);
		   }
		 
		}

	
	document.getElementById('selected_clusters').value = selectedClusters;
	allClusters = selectedClusters;
	
	  $$('#contents tr').each(function(item) {
  	    item.observe('mouseover', function() {
  	    	$(this).addClassName('selectedRow');
  	    });
  	    item.observe('mouseout', function() {
  	    	$(this).removeClassName('selectedRow');
  	    });
  	    item.observe('click', function() {
  	   
  	    	var all = document.getElementById('contents').rows.item(1);
  	    	var allGroups = document.getElementById('contents').rows.item(1).cells.item(0);
  	    	if((item != all) && allGroups != null && allGroups.innerHTML != "" && allGroups.innerHTML.trim() != "") { //all groups checked ignore other toggles
	    			return;
	    	    		
	    	    }
  	    	
  	    	var allID = item.cells.item(3).getElementsByTagName('input')[0];
  	    	var all = item.cells.item(0);
  	    	if(allID.id == "c1000000_count"){ //All conections was clicked
  	    		if(all != null && all.innerHTML != "" && all.innerHTML.trim() != "") { //toggle check marks
  	    			checkAllRows('contents','jds_count',false,allID.value);
  	    			document.getElementById('selected_clusters').value = "";	
  	    			
  	    	    }
  	    		else {
  	    			
  	    			checkAllRows('contents','jds_count',true,allID.value);
  	    			document.getElementById('selected_clusters').value = allClusters;	
  	    		}
  	    		return;	
  	    	}
  	    	
  	    	if (item.cells.item(3).innerHTML == null || item.cells.item(0).innerHTML == "" || item.cells.item(0).innerHTML.trim() == "") {
  	    		item.cells.item(0).innerHTML = "&#x2713;"; 
  	    	}
	    	
	    	else {
	    		item.cells.item(0).innerHTML = null; 
	    	}
  	    	getTableValues('contents',3);
  	    });
  	});
}

function populateContactsTable(id,tableData) {
	
	if(tableData.length == 0) {
		createNoFriendsTable("You have no contacts");
		return;
	}
	
	var tbodyElem = document.getElementById(id);
	var trElem, tdElem;
	var clusterid = 0;
	var CHECK_MARK ="&#x2713;";
	document.getElementById('selected_groups').value = "All groups";
	
	var ii= 1;
	for (var i in tableData) {
		
		 trElem = tbodyElem.insertRow(tbodyElem.rows.length);
		   // first column
		   tdElem = trElem.insertCell(trElem.cells.length); 
		   tdElem.innerHTML =   CHECK_MARK;
		  tdElem = trElem.insertCell(trElem.cells.length); 
		   tdElem.innerHTML =    i;
		
			 tdElem = trElem.insertCell(trElem.cells.length); 
			
			   var input = document.createElement("input");
			   input.setAttribute("type", "hidden");
			   input.setAttribute("name", "c" + ii + "_" + tableData[i]);
			   input.setAttribute("id", "c" + ii + "_" + tableData[i]);
			  
			   input.setAttribute("value", tableData[i]);
			 
			   tdElem.appendChild(input);
			   ii++;
			
		}
	
	  $$('#contact_contents tr').each(function(item) {
  	    item.observe('mouseover', function() {
  	    	$(this).addClassName('selectedRow');
  	    });
  	    item.observe('mouseout', function() {
  	    	$(this).removeClassName('selectedRow');
  	    });
  	    item.observe('click', function() {
  	    	
  	    	var all = document.getElementById('contact_contents').rows.item(0);
  	    	var allGroups = document.getElementById('contact_contents').rows.item(0).cells.item(0);
  	    	if((item != all) && allGroups != null && allGroups.innerHTML != "" && allGroups.innerHTML.trim() != "") { //all groups checked ignore other toggles
	    			return;
	    	    		
	    	    }
  	    	
  	    	var allID = item.cells.item(2).getElementsByTagName('input')[0];
  	  
  	    	var all = item.cells.item(0);
  	    	if(allID.id == "c1_" + allID.value){ //All conections was clicked
  	    		if(all != null && all.innerHTML != "" && all.innerHTML.trim() != "") { //toggle check marks
  	    			checkAllRows('contact_contents','contacts_count',false,allID.value);
  	    			document.getElementById('selected_groups').value = "";	
  	    	    		
  	    	    }
  	    		else {
  	    			checkAllRows('contact_contents','contacts_count',true,allID.value);
  	    		}
  	    		return;	
  	    	}
  	    
  	    	
  	    	if (item.cells.item(2).innerHTML == null || item.cells.item(0).innerHTML == "" || item.cells.item(0).innerHTML.trim() == "") {
  	    		item.cells.item(0).innerHTML = "&#x2713;"; 
  	    	
  	    	}
	    	
	    	else {
	    		item.cells.item(0).innerHTML = null; 
	    	}
  	    	getTableValues('contact_contents', 2);
  	 
  	    });
  	});
}

function getFriendsAndContacts() {
	//console.log("sending request...");
	var url = 'index2.php?option=com_ajax&no_html=1&action=getConnections';
	var myAjax = new Ajax.Request(url, {method: 'get', parameters: '', onComplete: processFriendsAndContacts});
}

function processFriendsAndContacts(oReq, oJSN) {
	
	//console.log("receving request...");
    var data = oReq.responseText.evalJSON();
    //console.log("data::");
   
    populateTable("contents",data["jds"]);
    populateContactsTable("contact_contents",data["contacts"]);
}

function getTableValues(element,index) {
	var count=0;
	var oTable = document.getElementById(element);
	var RowsLength = oTable.rows.length;
	var selected = "";
	
	for (var i=0; i < RowsLength; i++)
	{
	    if((element == "contents" && i <= 1) || (element == "contact_contents" && i == 0))
	    	continue;

	    		
		var oCells = oTable.rows.item(i).cells;

	    var CellsLength = oCells.length;
	  
	    if ((oCells.item(0) != null && oCells.item(0).innerHTML != null && oCells.item(0).innerHTML != "" && oCells.item(0).innerHTML.trim() != "")) {
	   
			    val = oCells.item(index).getElementsByTagName('input')[0].value;
			   
			    count = count + parseInt(val);
			    
			    if(element == "contents") {
			    	  var clusterid = oCells.item(index - 1).getElementsByTagName('input')[0].value;
			    	selected = selected + "|" + clusterid;
			    	
			    }
			    else {
			    	  var groupName =  oCells.item(1).innerHTML;
			    	selected = selected + "|" + groupName;
			    	
			    }
	    }
	}
	
	if(element == "contents")
		document.getElementById('selected_clusters').value = selected;
	else
		document.getElementById('selected_groups').value = selected;
	
	if(element == 'contents')
		document.getElementById('jds_count').innerHTML = count;
	else
		document.getElementById('contacts_count').innerHTML = count;

}

function checkAllRows(element,updated,check,value) {
	
	var oTable = document.getElementById(element);
	var RowsLength = oTable.rows.length;
	for (var i=0; i < RowsLength; i++)
	{
	    var oCells = oTable.rows.item(i).cells;
	    var CellsLength = oCells.length;
	    if(oCells != null && oCells.item(0) != null) {
	    		if(check)
	    			oCells.item(0).innerHTML = "&#x2713;";
	    		else 
	    			oCells.item(0).innerHTML = null;
	    }
	    
	}
	if(check)
		document.getElementById(updated).innerHTML = value;
	else
		document.getElementById(updated).innerHTML = 0;

}

function addNewGroupLink() {
	
}

function saveAllClusters(id) {
	var tbodyElem = document.getElementById(id);
	var trElem, tdElem;
	var clusterid = 0;
	var selectedClusters = "";
	
	var oTable = document.getElementById(id);
	var RowsLength = oTable.rows.length;
	for (var i=0; i < RowsLength; i++)
	{
		var oCells = oTable.rows.item(i).cells;
	    var CellsLength = oCells.length;
	    var clusterid = oCells.item(3).getElementsByTagName('input')[0].value;
	    selectedClusters = selectedClusters + "|" + clusterid;
	}

	document.getElementById('selected_clusters').value = selectedClusters;
}





