/*------------------------------------------------------
|   Load JavaScript functions
+------------------------------------------------------*/
function addLoadEvent(func){
	var oldonload = window.onload;
	if(typeof window.onload != 'function'){
		window.onload = func;
	}else{
		window.onload = function(){
			oldonload();
			func();
		}
	}
}
/*---------------------
|  Button Rollover
+----------------------*/
function Rollover(targetpicture,newpicture){
	document.getElementById(targetpicture).src = "/img/"+newpicture
}

function Rollover1(obj,newpicture){
	obj.src = "/img/"+newpicture;
}

/*----------------------
|  onclick open URL
+-----------------------*/
function go(Destination){
	window.location.href = Destination;
}

/*----------------------------------
|   Insert Edit Profile menu
+----------------------------------*/
var EditProfileMenu=new Array("Info","Personal","Education","Career","Investments","Indexes", "My Pictures","Account Settings","Admin Panel");
var setActive = "";
var ProfileUserID = '';
/* Parameters
string: role [Investor|Student|Mentor]
integer: set menu index number to set as active
true|false: display Admin Panel item
*/

function insertEditProfileNavigation(Role,activeLink,displayAdmin){

   if(Role=="Student")  {
      EditProfileMenu=new Array("Info","Personal","Education","Career","Investments","Indexes", "Tasks", "My Pictures","Account Settings","Admin Panel");
      if(parseInt(activeLink)>5) activeLink++;
   }

   var linkUrl = "";

	for(menuItem in EditProfileMenu){
		if(EditProfileMenu[menuItem] == "Admin Panel" && displayAdmin == false){
			return false;
		}

      itemLink=EditProfileMenu[menuItem].replace(/ /,"_");
      linkUrl = "/profile/edit/"+itemLink.toLowerCase() + "/" + ProfileUserID;
      if(displayAdmin) linkUrl = "/admin" + linkUrl;
      if(EditProfileMenu[menuItem] == "Admin Panel") linkUrl = "/admin";
		if(menuItem == activeLink){ setActive = " style=\"color: #036;\""; };
		document.write("<div style=\"position:relative;\"><span"+setActive+" onclick=\"window.location.href='"+linkUrl+"'\">"+EditProfileMenu[menuItem]+"</span></div>");

		setActive = "";

	}
}

/*------------------------------------------------------
|   Insert page navigation with left and right arrows
+------------------------------------------------------
Works with the #searchStudentPageNav selector, set at width: 790px by default

Parameters:
integer: display numbers of pages
true|false: display left double arrow
true|false: display left single arrow
integer: pagination index start
pageEnd: pagination index end
true|false: display right single arrow
true|false: display right double arrow
integer: what page is active
*/
function toggleArrow(State,targetArrow){
	var arrowPic = (targetArrow == 'doublearrow' || targetArrow == 'doublearrow1') ? "" : "2";
	
	if(State == true){
		document.getElementById(targetArrow).src = "/img/arrow-double_blue"+arrowPic+".gif";
	}
	else{
		document.getElementById(targetArrow).src = "/img/arrow-double_grey"+arrowPic+".gif";
	}
}
	
function pageNavigation(totalPages,leftDoubleArrow,leftSingleArrow,pageStart,pageEnd,rightSingleArrow,rightDoubleArrow,activePage){
	if(totalPages>0){ document.write("<span><strong>"+totalPages+" Pages</strong></span> "); }
	if(leftDoubleArrow == true){ document.write("<span>&lt;&lt;</span> "); }
	if(leftSingleArrow == true){ document.write("<span>&lt;</span> "); }
	
	for(i=pageStart; i<=pageEnd; i++){
		if(i==activePage){
			document.write("<span style=\"color: #fff; background-color: #036;\">"+i+"</span> ");
		}
		else{
			document.write("<span>"+i+"</span> ");
		}
	}
	
	if(rightSingleArrow == true){ document.write("<span>&gt;</span> "); }
	if(rightDoubleArrow == true){ document.write("<span class=\"pageNavArrow\" onmouseover=\"toggleArrow(true,'doublearrow')\" onmouseout=\"toggleArrow(false,'doublearrow')\"><img src=\"/img/arrow-double_grey.gif\" width=\"6\" height=\"6\" style=\"padding: 5px 0px 4px 0px; margin-bottom: -3px;\" id=\"doublearrow\" /></span>"); }
}

/*----------------------------------
|   For all search fields
+----------------------------------
Works by adding the 'searchField' class attribute on an 'input' tag
- When clicking the field, the default text should disappear
- When leaving the field, if no text has been entered, revert to original value.  Otherwise leave the value that has been entered
Example: <input type="text" value="Search Messages" class="searchField" />
*/
function prepareSearchField(){
	var inputFields = document.getElementsByTagName('input');
	for(var i=0; i<inputFields.length; i++){
		if(inputFields[i].className == "searchField"){
			var searchField = inputFields[i];
			var searchFieldValue = searchField.getAttribute('value');
			searchField.onclick = function(){
				this.value = "";
			}
			searchField.onblur = function(){
				if(this.value == ""){this.value = searchFieldValue};
			}
		}
	}
}

/*-------------------------------------------------------------+
|   Toggle formatting button between 'Prompt' and 'Advanced'   |
+--------------------------------------------------------------*/
function toggleFormattingButtons(dropdown, instance){

	if(!instance)	{
		instance = "FormattingButtons";
	}

	var optionIndex = dropdown.selectedIndex;
	var standardFormat = document.getElementById('standard'+instance);
	var advancedFormat = document.getElementById('advanced'+instance);

	if(optionIndex == 0){
		advancedFormat.style.display = "none";
		standardFormat.style.display = "block";
	}
	else{
		standardFormat.style.display = "none";
		advancedFormat.style.display = "block";
	}
}

function addComboBox(ResEleName, SrcEleId, ResEleId, disabled)  {
  
  var resNode = document.createElement('select');
  resNode.name = ResEleName; //"remHour[]"

  if(ResEleId)
  resNode.id   = ResEleId;

  var elSel = document.getElementById(SrcEleId);//'rem_hours'
  var i;
  //alert(elSel.length);
  for (i = 0; i < elSel.length; i++) {
    var elOptNew = document.createElement('option');
    elOptNew.text = elSel.options[i].text;
    elOptNew.value = elSel.options[i].value;
    if(elSel.options[i].selected) {
      elOptNew.selected=true;
     };
    try {
      resNode.add(elOptNew, null); // standards compliant; doesn't work in IE
    } catch(ex) {
      resNode.add(elOptNew); // IE only
    }
  }
  if(disabled)
  resNode.disabled=true; //setting disabled
  return resNode;
}

function toggleTab(TabID){
	var allTabs = new Array("overview","info","personal","education","career","investment","tasks");
	// Reset all tabs to inactive
	for(i=0; i<allTabs.length; i++){
		document.getElementById(allTabs[i]+"Tab").src = "/img/tab_"+ allTabs[i] +".jpg";
	}
	
	// Set clicked tab to active
	var clickedTab = TabID.substring(0,TabID.length-3);
	document.getElementById(TabID).src = "/img/tab_"+ clickedTab +"_white.jpg";
	document.getElementById(TabID).newprop = "/img/tab_"+ clickedTab +"_white.jpg";
	
	// Hide all tab tables
	for(i=0; i<allTabs.length; i++){
      //alert(allTabs[i]);
		//if(allTabs[i]==undefined) alert(i + "undefined")
      if(document.getElementById(allTabs[i]+"Table"))
      document.getElementById(allTabs[i]+"Table").style.display = "none";
	}
	document.getElementById("portfolioTable").style.display = "none";
   if(document.getElementById("tasksHistoryTable"))   {
      document.getElementById("tasksHistoryTable").style.display = "none";
   }
	// Reveal the table matching the clicked tab
	document.getElementById(clickedTab+"Table").style.display = "";
}

function highlightTab(TabID,state){
	var activeTab = document.getElementById(TabID);
	if(activeTab.src.indexOf('white') < 0){
		if(state){
			activeTab.newprop = activeTab.src;
			activeTab.src = "/img/tab_" +TabID+ "_roll.jpg";
		}else{
			activeTab.src = activeTab.newprop;
		}
	}
}

function showPortfolio(){
	document.getElementById("investmentTable").style.display = "none";
	document.getElementById("portfolioTable").style.display = "block";
}

function backPortfolio(){
	document.getElementById("investmentTable").style.display = "";
	document.getElementById("portfolioTable").style.display = "none";
}

function showTaskHistory(){
	document.getElementById("tasksTable").style.display = "none";
	document.getElementById("tasksHistoryTable").style.display = "block";
}

function backTaskHistory(){
	document.getElementById("tasksTable").style.display = "";
	document.getElementById("tasksHistoryTable").style.display = "none";
}

//Ajax pagination used with cakephp pagination helper

function loadPiece(href,divName) {

	 $(divName).load(href, {}, function(){
		  var divPaginationLinks = divName+" table td#searchStudentPageNav a";
		  $(divPaginationLinks).click(function() {     
				var thisHref = $(this).attr("href");
				loadPiece(thisHref,divName);
				return false;
		  });
	 });
}

var ContactsInList = new Array();
var SelectedContactsCount=0;

function loadContactListAjaxAction(href,divName) {

	 $(divName).load(href, {}, function(){
	 
	 	$(divName + ' ul li').mouseover(function()	{
			if($(this).attr('class')!='selected')	{
				$(this).attr({'class':'selected_tmp'});
			}
		});

		$(divName + ' ul li').mouseout(function()	{
			if($(this).attr('class')!='selected')	{
				$(this).attr({'class':''});
			}
		});

		$(divName + ' ul li').click(function()	{

			var tmp = $('#UserContactSelection').val();

			if(ContactsInList.length==0 && tmp!="")	{

				ContactsInList = tmp.split(',')
			}
			
			var user_id_arr = $(this).attr('id').split('_');
			var user_id = user_id_arr[1];

			if($(this).attr('class')=='selected')	{
				$(this).attr({'class':''});

				ContactsInList = jQuery.grep(ContactsInList, function(value) {
					return value != user_id;
				});

				SelectedContactsCount--;
			}	else	{
				
				//if(jQuery.indexOf(user_id, ContactsInList )==-1)	{
					ContactsInList.push(user_id);
				//}

				$(this).attr({'class':'selected'});
				SelectedContactsCount++;
			}

			//alert(ContactsInList[0])
			//	alert(ContactsInList[1]);
			//alert(ContactsInList[2]);
			//alert(ContactsInList.join(','))

			$('#SelectedContactsCount').html(SelectedContactsCount);
			$('#UserContactSelection').val(ContactsInList.join(','));
			//alert($('#UserContactSelection').val())
			
		});

		SelectedContactsCount=parseInt($('#SelectedContactsCount').html());

	 });
}

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 InvokeSendMessageDialog(obj)	{
		
		var urlId = $(obj).attr('id')

		if(urlId.indexOf('invokeSendMessage_')!=-1)	{
			var idVars = urlId.split('_');
			var userId = idVars[1];
			alert(userId);
			$('#ToTo0').val(userId);
			$('#recipient').html($('#myContactName_'+userId).html())
			tb_show("Send Message", "#TB_inline?height=470&width=540&inlineId=sendMessage&modal=true");
			//#TB_inline?height=470&width=540&inlineId=sendMessage&modal=true
		}
}

function InvokeAddContactDialogAjax(obj)	{
		var urlId = $(obj).attr('id')

		if(urlId.indexOf('invokeAddContact_')!=-1)	{
			var idVars = urlId.split('_');
			var userId = idVars[1];
			//alert(userId);
			$('#UserContactContactId').val(userId);
			
			tb_show("Add Contact", "/contacts/addContactAjax/"+userId+"?height=auto&width=540&modal=true");
			
			
		}
}

function InvokeAddContactDialog(obj)	{
		
		var urlId = $(obj).attr('id');

		if(urlId.indexOf('invokeAddContact_')!=-1)	{
			var idVars = urlId.split('_');
			var userId = idVars[1];
			//alert(userId);
			$('#UserContactContactId').val(userId);

			var username = $('#myContactName_'+userId).html();
			
			$('table#addContactTable tr td b').html('<a href="/profile/index/'+userId+'">'+username+'</a>');
			var userGroupNameCat = $('#userGroup_'+userId).html() + "s";
			
			$("#ContactsCatDP").prepend("<option>"+userGroupNameCat+"</option>");
			
			//alert(userGroupNameCat);
			tb_show("Add Contact", "#TB_inline?height=300&width=540&inlineId=addContact&modal=true")
		}
}

function tb_ShowLoginBox(idOfBox)	{
	tb_show('Login Do!',"#TB_inline?height=410&width=540&inlineId="+idOfBox+"&modal=true",'');
}

function showUserEmblems(userId, eleID){
	$.ajax({
	url: '/forum/rating/showUserEmblems/'+userId,
	success: function(data) {
		$('#'+eleID).html(data);
	}
	});
}

function Auth()	{
	if($('#wrongPassword').length==1)	{ //1 means login form is loaded
		tb_show('Login Do!',"#TB_inline?height=auto&width=540&inlineId=wrongPassword&modal=true",'');
		return false;
	}
	return true;
}

function Authorize(){
	var result = null;
	$.ajax({
	url: '/users/is_authorized_ajax',
	dataType: 'json',
	async: false,
	success: function(data) {
			result = data;
		}
	});
	return result;
}

function tb_show_guest_upgrade()	{
	tb_show('Upgrade Account!',"/users/guest_upgrade?height=auto&width=540&modal=true");
	return false;	
}

function tb_show_login_box(qs)	{
	var params = '';
	if(qs!="")	{
		params = qs;
	}
	tb_show('Login Ajax!',"/users/login_ajax?height=auto&width=540&modal=true"+params);
	return false;
}

function tb_copyright(copyright)	{
	if($("#TB_window").length > 0)	{

		if(!copyright)	{
			copyright = 'Copyright &copy; Rising Farmworker Dream Fund, 2009 - 2011. All Rights Reserved';
		}

      if($("div.CopyrightNotice").length <=0 ) {
		   $("#TB_window").append('<div class="CopyrightNotice" style="clear: both; padding-top: 5px; text-align: center;margin-bottom:3px;">'+copyright+'</div>');
      }
	}
}

function doInvest(Url)	{
	
	//if(!Auth()) return false;
	tb_show('Invest In Me!', Url);
}

function myCart(Url)	{
	
	//if(!Auth()) return false;
	tb_show('My Cart Contents', Url);
}

function addContact(Url)	{
	if(!Auth()) return false;
	tb_show('Add Contact!', Url);
}


function sendMessage(Url)	{
	if(!Auth()) return false;
	tb_show('Send Message!', Url);
}	

function ValidateAddProfileLinkRecipient(formData, jqForm, options) { 
	
	if(num_profile_link_recipients == 5) {alert('Maximum 5 recipients could be added at this time'); return false;}
	
	if($.trim($('#ToName').val())=='')	{
		alert('Enter recipient\'s name')
		$('#ToName').focus();
		return false
		//$('#ToNameError').show();return false;
	}//	else	$('#ToNameError').hide();

	var email = $.trim($('#ToEmail').val());

	if(email=='' || !echeck(email))	{
		alert('Enter valid email address')
		$('#ToEmail').focus();
		return false
		//$('#ToEmailError').show();return false;
	}//	else	$('#ToEmailError').hide();

	for(var i=1;i<=5;i++)	{
		if($('#RecipientEmail'+i).length > 0 && $('#RecipientEmail'+i).val()==email)	{
			alert("Recipient already added to recipient list"); return false;
		}
		//return false;
	}


	return true; 
}
 
function ProfileLinkRecipientAdded(responseText, statusText, xhr, $form)  {

	$('#ToEmail').val('');$('#ToName').val('');

	num_profile_link_recipients++;

	return false;

	 /*(jQuery.trim(responseText)=="Success") {
		tb_remove();
		location.reload();
	 }*/
}

function removeRcp(id)	{
	$("#"+id).html('');
	num_profile_link_recipients--;
}

function MM_preloadImages() { //v3.0
    //alert("He");
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
