var freezeNav = false;

//button setup for on page/ajax loads
function buttonSetup(){
    //handlers for mousedown and mouseup events for normal buttons
	$('.button, .buttonleft, .buttonright').not('.selected').not('.disabled').bind('mousedown', function(){
        $(this).addClass('active');
        $(document).one("mouseup", function(){
            $('.active').removeClass('active');
        });
	});

	//make text unselectable in IE - accomplished for safari and ff with css
	if($.browser.msie){
	    $('.button *, .buttonleft *, .buttonright *').attr("unselectable", "on");
	}
}

function handleHistoryChange(newLocation, historyData) {
	// use the history data to update our UI
	updateUI(newLocation, historyData);
}

//Loads the href of a link into the content panel
function navigateA(oLink, pbFreezeNav){
	bFreezeNav = arguments.length > 1 ? (pbFreezeNav ? true : false) : false;
	return navigate(oLink.href, b64_md5(oLink.href), true, bFreezeNav);
}

//Global array to help with remembering ajax scroll position
aScrolls = new Array();

//current navigate request object
var navRequestObj = null;

//Loads a location into the #content div
function navigate(pstrURL, pstrAbbrv, pbAddHistory, pbFreezeNav){
    bFreezeNav = arguments.length > 3 ? (pbFreezeNav ? true : false) : false
	if(pstrURL.length && (!bFreezeNav || !freezeNav) && !formIsModified()){
		if(typeof(pstrAbbrv) == 'undefined'){
			pstrAbbrv = b64_md5(pstrURL);
		}
        aScrolls[pstrAbbrv] = 0;

        //preserve scroll position for history
		if($('#main')[0].scrollTop > 0){
			aScrolls[$('#currentHash').val()] = $('#main')[0].scrollTop;
		}

		//Save the location they want in the curent page
		$('#currentLocation').val(pstrURL);
		$('#currentHash').val(pstrAbbrv);

		if(pbAddHistory !== false){
			dhtmlHistory.add(pstrAbbrv, pstrURL);
		}

		//Append the loading div
		showLoading(true);

		iUserID = $("input:hidden[@name='loggedInUser']").val();

		//Load the new content
        //$('#content').load(pstrURL, {pageNav: true, userID: iUserID}, function(){changeTabs(pstrURL);});

		// Load the new content with a jQuery ajax request so we can abort if we have to
		if( navRequestObj !== null && navRequestObj.abort ){
			//Abort the AJAX request
			navRequestObj.abort();
		}

		freezeNav = true;
		navRequestObj = $.ajax({
			url: pstrURL,
			type: "POST",
			dataType: "html",
			data: { pageNav: true, userID: iUserID },
			complete: function(res, status){
				// If successful, inject the HTML into all the matched elements
				if ( status == "success" || status == "notmodified" ){
					$('#content').html( res.responseText );
				}
				changeTabs(pstrURL);

				navRequestObj = null; //so IE can deal
				freezeNav = false;
			}
		});

    }
	return false;
}

//Append the loading throbber to #content, where it will be whacked when the content finishes loading
function showLoading(){
	$('#main').append('<div class="loading_throbber" style="background-color:#FFF; position:fixed; top:40%; left:50%; border:1px solid #ddd;"><img src="/images/throbber.gif" style="padding:7px;"></div>');
}

//Hide the loading throbber
function hideLoading(){
	$('.loading_throbber').remove();
}

//Takes a URL and decides whether to change tabs
function changeTabs(pstrURL){
	pstrURL = pstrURL.toLowerCase();

	var strTab = '';
        if(pstrURL.indexOf('/internal/alerts.php') != -1){
          strTab = 'tab_alerts';
        }
        else if(pstrURL.indexOf('/internal/activities.php') != -1 || pstrURL.indexOf('/internal/application_budget.php') != -1 || pstrURL.indexOf('/internal/reimbursements.php') != -1 || pstrURL.indexOf('/internal/summary.php') != -1 || pstrURL.indexOf('/internal/activity.php') != -1 || pstrURL.indexOf('/internal/admin_activity.php') != -1){
          strTab = 'tab_application';
        }
        else if(pstrURL.indexOf('/internal/admin/settings/userprofile.php') != -1){
                if(pstrURL.indexOf("myprofile=1") != -1){
                        strTab = 'tab_profile';
                }
                else{
                        strTab = 'tab_settings';
                }
        }
        else if(pstrURL.indexOf('/internal/admin/settings/') != -1){
          strTab = 'tab_settings';
        }
        else if(pstrURL.indexOf('/internal/admin/') != -1){
          strTab = 'tab_reports';
        }



  //Clear the currently selected tab and set the new one
  $('div#header ul li a').removeClass('current');
  if($('#' + strTab).size()){
    $('#' + strTab).addClass('current');
  }
}

//when the changeTabs function just won't cut it, and we need to force a certain tab to be selected.
function forceTab(pstrTab){
    //Clear the currently selected tab and set the new one
    $('div#header ul li a').removeClass('current');
    if($('#' + pstrTab).size()){
        $('#' + pstrTab).addClass('current');
    }
}

function openPopup(strLocation, strID, height, width, bNotResizable){
    strID = strID ? strID : 'default';	//Default ID
	height = height ? height : 400;	//Default height
	width = width ? width : 500;	//Default width
    bResizable = bNotResizable ? 0 : 1;

    var newWin;
    newWin = window.open(strLocation, strID, 'resizable=' + bResizable + ',scrollbars=auto,width=' + width + ',height=' + height + ',locationbar=no,toolbar=no');
	newWin.focus();
}

//Basic function that checks if the value is in the array, similar to php's in_array() (used by jquery.alphanumeric.js)
function in_array(pstrNeedle, paHaystack){
	var i;
	for(i = 0; i < paHaystack.length; i++){
		if(pstrNeedle === paHaystack[i]){
			return true;
		}
	}
	return false;
}

//Put The Commas In the Numbers
function commaSplit(srcNumber) {
	var txtNumber = '' + srcNumber;
	if (isNaN(txtNumber) || txtNumber == "") {
		return srcNumber;
	}
	else {
		var rxSplit = new RegExp('([0-9])([0-9][0-9][0-9][,.])');
		var arrNumber = txtNumber.split('.');
		arrNumber[0] += '.';
		do {
			arrNumber[0] = arrNumber[0].replace(rxSplit, '$1,$2');
		}
		while (rxSplit.test(arrNumber[0]));

		if (arrNumber.length > 1) {
			return arrNumber.join('');
		}
		else {
			return arrNumber[0].split('.')[0];
	    }
	}
}

//toggles the filters...
function toggleFilter(strID){
    $('#' + strID).slideToggle('fast');
    $('#showFilterButton').toggleClass('bluearrowdown').toggleClass('bluearrowright');
    if($('#showFilterButton').attr('class') == 'bluearrowright'){
		$('#removeFilterButton').hide();
		$('#showFilterButton').show();
    }
    else if($('#showFilterButton').attr('class') == 'bluearrowdown'){
		$('#showFilterButton').hide();
		$('#removeFilterButton').show();
	}
}

function showFilter() {
	$('.filterdiv>form').show();
	$('#showFilterButton').hide();
	$('#removeFilterButton').show();
}

function hideFilter() {
    $('.filterdiv>form').hide();
    $('#removeFilterButton').hide();
    $('#showFilterButton').show();
}

/**********************************************
 *		NOTE JAVASCRIPT
 *********************************************/

function saveNote(poNoteDiv, pbSend){
	bSend = pbSend == undefined || !pbSend ? 0 : 1;

    if(poNoteDiv.find('#title').size() && !poNoteDiv.find('#title').val().replace(/(^\s*)|(\s*$)/g, '').length){
		alert('Please enter a title for this note before ' + (bSend ? 'sending.' : 'saving.'));
		return false;
	}
	if(!poNoteDiv.find('#content').val().replace(/(^\s*)|(\s*$)/g, '').length){
		alert('Please enter a description for this note before ' + (bSend ? 'sending.' : 'saving.'));
		return false;
	}

    $.ajax({
		url: '/internal/noteajax.php',
		type: 'POST',
		data: ({ownerID : poNoteDiv.parent().siblings('#owner_id').val(),
		       ownerType : poNoteDiv.parent().siblings('#owner_type').val(),
                       startYear: poNoteDiv.parent().siblings('#start_year').val(),
		       noteOwner: poNoteDiv.parent().siblings('#note_owner').val(),
		       noteType: poNoteDiv.parent().siblings('#note_type').val(),
		       task: poNoteDiv.attr('note_id') == 'NEW' ? 'addNote' : 'saveNote',
		       noteID: poNoteDiv.attr('note_id'),
		       replyTo: poNoteDiv.attr('reply_to'),
		       content: poNoteDiv.find('#content').val(),
               send: bSend,
		       title: poNoteDiv.find('#title').size() ? poNoteDiv.find('#title').val() : ''}),
		success: function(data){
					if(bSend){
                        poNoteDiv.parent().find('#REPLY_BUTTON').show();
                    }
                    else{
                        poNoteDiv.parent().find('#status').html(poNoteDiv.attr('reply_to') == 0 ? ' (unsent)' : ' (unsent reply)');
                        poNoteDiv.parent().find('#status').show();
                    }
                    poNoteDiv.replaceWith(data);
					return false;
				}
	});
	return false;
}

function cancelNote(poNoteDiv){
	if(poNoteDiv.attr('note_id') == 'NEW'){
		if(poNoteDiv.attr('reply_to') == 0){
			poNoteDiv.parent().remove();
		}
		else{
			poNoteDiv.siblings('#REPLY_BUTTON').show();
			poNoteDiv.remove();
		}
	}
	else{
		$.ajax({
			url: '/internal/noteajax.php',
			type: 'POST',
			data: ({ownerID : poNoteDiv.parent().siblings('#owner_id').val(),
			       ownerType : poNoteDiv.parent().siblings('#owner_type').val(),
                               startYear: poNoteDiv.parent().siblings('#start_year').val(),
			       task: 'getNote',
			       noteID: poNoteDiv.attr('note_id')}),
			success: function(data){
						poNoteDiv.replaceWith(data);
						return false;
					}
		});
	}
	return false;
}

function removeNote(poNoteDiv){
	if(confirm('Are you sure you want to remove this note?' + (poNoteDiv.attr('reply_to') == 0 && poNoteDiv.siblings('.note_div').size() ? ' All replies to this note will be removed as well.' : ''))){
		$.ajax({
			url: '/internal/noteajax.php',
			type: 'POST',
			data: ({ownerID : poNoteDiv.parent().siblings('#owner_id').val(),
			       ownerType : poNoteDiv.parent().siblings('#owner_type').val(),
                               startYear: poNoteDiv.parent().siblings('#start_year').val(),
			       task: 'removeNote',
			       noteID: poNoteDiv.attr('note_id')}),
			success: function(){
						if(poNoteDiv.attr('reply_to') == 0){
							if(poNoteDiv.parent().siblings('#single_note').val() == '0'){
								poNoteDiv.parent().remove();
							}
							else{
								var strHtml = '<div class="note_div" note_id="NEW" reply_to="0"><div style="color: black;"><a href="#" onclick="return saveNote($(this).parent().parent());">save</a></div>';
								strHtml += '<label class="over-apply" title="Description" for="content" onclick="$(this).hide(); $(this).next().focus();">Description</label><textarea id="content" onfocus="$(this).prev().hide();" onblur="$(this).val().length ? $(this).prev().hide() : $(this).prev().show();"></textarea></div>';
								poNoteDiv.replaceWith(strHtml);
							}
						}
						else{
							poNoteDiv.parent().find('#status').hide();
							poNoteDiv.siblings('#REPLY_BUTTON').show();
							poNoteDiv.remove();
						}
						return false;
					}
		});
	}
	return false;
}

function openNote(poNoteWrapper, poNoteDiv){

	//setup the html
	mNoteID = poNoteDiv == undefined || !poNoteDiv ? 'NEW' : poNoteDiv.attr('note_id');
	strHtml = '<div class="note_div" note_id="' + mNoteID + '" reply_to="0">';
	strHtml += poNoteWrapper.find('#single_note').val() == '0' ? '<label class="over-apply" style="font-size: 14px; ' + (mNoteID == 'NEW' ? '' : 'display: none;') + '" title="Title" onclick="$(this).hide(); $(this).next().focus();">Title</label><input type="text" maxlength="255" id="title" onfocus="$(this).prev().hide();" onblur="$(this).val().length ? $(this).prev().hide() : $(this).prev().show();" value="' + (mNoteID == 'NEW' ? '' : poNoteDiv.find('#title').html()) + '">' : '';
	strHtml += '<div style="color: black;"><a href="#" onclick="return saveNote($(this).parent().parent());">save</a> | <a href="#" onclick="return cancelNote($(this).parent().parent());">cancel</a></div>';
	strHtml += '<label class="over-apply" style="' + (mNoteID == 'NEW' ? '' : 'display: none;') + '" title="Description" for="content" onclick="$(this).hide(); $(this).next().focus();">Description</label><textarea id="content" onfocus="$(this).prev().hide();" onblur="$(this).val().length ? $(this).prev().hide() : $(this).prev().show();">' + (mNoteID == 'NEW' ? '' : poNoteDiv.find('#content').html()) + '</textarea>';
	strHtml += '</div>';


	//show the editable html & hide any static stuff
	iIndex = mNoteID == 'NEW' ? 1 : poNoteWrapper.children().index(poNoteDiv.parent().get(0));
	mNoteID == 'NEW' ? poNoteWrapper.find('#NEW_BUTTON').after('<div class="notebox" style="height: 100%;">' + strHtml + '</div>') : poNoteDiv.replaceWith(strHtml);
	poNoteWrapper.children(':eq(' + iIndex + ')').find('#content').growfield({min: 38});

	return false;
}

function openReply(piReplyTo, poNoteDiv, pbSend){

	//setup the html
	mNoteID = poNoteDiv == undefined || !poNoteDiv ? 'NEW' : poNoteDiv.attr('note_id');
    bSend = pbSend == undefined || !pbSend ? 0 : 1;
	strHtml = '<div class="note_div" note_id="' + mNoteID + '" reply_to="' + piReplyTo + '">';
	strHtml += '<div style="color: black;"><a href="#" onclick="return saveNote($(this).parent().parent(), ' + bSend + ');">' + (bSend ? 'send' : 'save') + '</a> | <a href="#" onclick="return cancelNote($(this).parent().parent());">cancel</a></div>';
	strHtml += '<label class="over-apply" style="' + (mNoteID == 'NEW' ? '' : 'display: none;') + '" title="Description" for="content" onclick="$(this).hide(); $(this).next().focus();">Description</label><textarea id="content" onfocus="$(this).prev().hide();" onblur="$(this).val().length ? $(this).prev().hide() : $(this).prev().show();">' + (mNoteID == 'NEW' ? '' : poNoteDiv.find('#content').html()) + '</textarea></div>';


	//show the editable html & hide any static stuff
	oParent = mNoteID == 'NEW' ? $('div [note_id="' + piReplyTo + '"]').parent() : poNoteDiv.parent();
	iIndex = mNoteID == 'NEW' ? oParent.children().size() : oParent.children().index(poNoteDiv[0]);
	oParent.find('#REPLY_BUTTON').hide();
	mNoteID == 'NEW' ? oParent.find('#REPLY_BUTTON').before(strHtml) : poNoteDiv.replaceWith(strHtml);
	oParent.children(':eq(' + iIndex + ')').find('#content').growfield({min: 38});
	return false;
}

function toggleNoteBox(poLink){
	oNoteBox = $(poLink).parent().parent().parent();
	var iHeight = 0;
	oNoteBox.children(':visible').each(function(){
		iHeight += $(this).height() + 15;
	});
	if(poLink.innerHTML == 'expand view'){
		oNoteBox.animate({
			height: iHeight + 'px'
			}, 250, function(){
				poLink.innerHTML = 'collapse view';
				oNoteBox.css('height', '100%');
				$.ajax({
					url: '/internal/noteajax.php',
					type: 'POST',
					data: ({ownerID : oNoteBox.siblings('#owner_id').val(),
					       ownerType : oNoteBox.siblings('#owner_type').val(),
                                               startYear: oNoteBox.parent().siblings('#start_year').val(),
					       task: 'markRead',
					       noteID: $(poLink).parent().parent().attr('note_id')}),
					success: function(){
							$(poLink).siblings('#status').html() == ' (unread)'  ? $(poLink).siblings('#status').hide() : '';
						}
					});
				});
	}
	else{
		oNoteBox.css('height', oNoteBox.height());
        oNoteBox.animate({
			height: '25px'
			}, 250, function(){ poLink.innerHTML = 'expand view' });
	}
}

function resetFormDefaults(){
    var aForms = $('.userInput');
    for(var i = 0; i < aForms.length; i++){
	  var oForm = aForms.get(i);
	  var el, opt, iCount = 0, j;
	  while (el = oForm.elements[iCount++]) {
	       switch (el.type) {
		    case 'text' :
		    case 'textarea' :
		    case 'password' :
		    case 'hidden' :
			 el.defaultValue = el.value;
			 break;
		    case 'checkbox' :
		    case 'radio' :
			 el.defaultChecked = el.checked;
			 break;
		    case 'select-one' :
		    case 'select-multiple' :
			 j = 0;
			 while (opt = el.options[j++])
			      opt.defaultSelected = opt.selected
		    break;
	       }
	  }
    }
    return false;
}

//stole this from populi...
function formIsModified() {
	var strConfirm = "You have not saved your current changes. Are you sure you want to navigate away? All unsaved changes will be lost.";
	var aForms = $('.userInput');
	var aIgnoreIDs = new Array('perkinsYear', 'ownerID', 'programSearch', 'cipcode', 'addNewConsortium', 'duplicateOldConsortium');

	for(var i = 0; i < aForms.length; i++){
		var oForm = aForms.get(i);
		var el, opt, hasDefault, iCount = 0, j, bQuit;
		while (el = oForm.elements[iCount++]) {
		    bQuit = false;
		    for(var i = 0; i < aIgnoreIDs.length; i++){
		    	if ( aIgnoreIDs[i] == el.id ) {
		    		bQuit = true;
		    	}
		    }
		    if ( bQuit || el.style.display == 'none' || el.style.visibility == 'hidden') {
		    	continue;
		    }

			switch (el.type) {
				case 'text' :
				case 'textarea' :
               case 'password' :
               case 'hidden' :
					if ( el.value.replace(/^\s+|\s+$/g,"") != el.defaultValue.replace(/^\s+|\s+$/g,"") ) {
						return !confirm(strConfirm);
					}
	               	break;
	         	case 'checkbox' :
	         	case 'radio' :
	               	if ( el.checked != el.defaultChecked ) {
	               		return !confirm(strConfirm);
	               	}
	               	break;
	         	case 'select-one' :
	         	case 'select-multiple' :
	         		j = 0, hasDefault = false;
	               	while (opt = el.options[j++])
                     	if ( opt.defaultSelected ) {
                     		hasDefault = true;
                     	}
	               	j = hasDefault ? 0 : 1;
	               	while (opt = el.options[j++])
                     	if ( opt.selected != opt.defaultSelected ) {
                     		return !confirm(strConfirm);
                     	}
	               	break;
			}
		}
	}
	return false;
}

function changeEntity(poSelect){
	if( $(poSelect).attr('page').length && !formIsModified() ){
		resetFormDefaults();
		var strUrl = '/internal/' + $(poSelect).attr('page') + '?ownerID=' + $(poSelect).val().split('_')[0] + '&ownerType=' + $(poSelect).val().split('_')[1];
		strUrl += $('#startYear').length ? '&startYear=' + $('#startYear').val() : '';
		navigate(strUrl);
	}
	else{
		$(poSelect).val($(poSelect).attr('firstval'));
	}
}

function changeYear(poSelect){
	if( $(poSelect).attr('page').length && !formIsModified() ){
		resetFormDefaults();
		var strUrl = '/internal/' + $(poSelect).attr('page') + '?startYear=' + $(poSelect).val();
		strUrl += $('#ownerID').length ? '&ownerID=' + $('#ownerID').val().split('_')[0] + '&ownerType=' + $('#ownerID').val().split('_')[1] : '';
		navigate(strUrl);
	}
	else{
		$(poSelect).val($(poSelect).attr('firstval'));
	}
}


/****************************************************************
 *
 *
 * 						CUSTOM FILTER STUFF
 *
 *
 ****************************************************************/

function changeFilterColumn(poSelect){
	var strType = $(poSelect).find('option:selected').attr('col_type');
	if( strType == 'TEXT' ){
		$(poSelect).parent().find('select[@name="filter_numeric_operators"]').hide();
		$(poSelect).parent().find('select[@name="filter_text_operators"]').show();
		$('#filter_value').replaceWith('<input type="text" style="margin: 0px 5px 0px 5px;" name="filter_value" id="filter_value" value="" />');
	}
	else if( strType == 'NUMERIC' ){
		$(poSelect).parent().find('select[@name="filter_text_operators"]').hide();
		$(poSelect).parent().find('select[@name="filter_numeric_operators"]').show();
		$('#filter_value').replaceWith('<input type="text" style="margin: 0px 5px 0px 5px;" name="filter_value" id="filter_value" value="" />');
		$('#filter_value').numeric();
	}
}

function addCondition(poButton){
	var oParent = $(poButton).parent();

	var oLogic = oParent.find('#filter_logic');
	var oCols = oParent.find('#filter_columns');
	var oOperators = oParent.find('.filter_operators:visible');
	var strValue = oParent.find('#filter_value').val();
	var strType = oCols.find('option:selected').attr('col_type');

	//don't do anything if they haven't entered a value
	if( !strValue.length ){
		return false;
	}

	var bFirst = $('.filter_condition').length ? 0 : 1;

	var strHtml = '<div class="filter_condition" style="margin-top: 5px;">';
	strHtml += '<a href="#" onclick="removeCondition(this); return false;" style="margin-right: 5px;" class="remove_condition_link" id="remove_condition_link_' + $('.filter_condition').length + '"><img src="/images/delete.gif" title="Remove" /></a>';
	strHtml += bFirst ? '' : '<span class="filter_logic">' + oLogic.find('option:selected').html() + ' </span>';
	strHtml += '<span class="filter_column">' + oCols.find('option:selected').html() + ' </span>';
	strHtml += '<span class="filter_operator">' + oOperators.find('option:selected').html() + ' </span>';
	strHtml += '<span class="filter_value">' + (strType == 'NUMERIC' ? strValue : "'" + strValue + "'") + ' </span>';
	strHtml += '<input type="hidden" name="customConditions[]" value="' + oLogic.val() + '|' + oCols.val() + '|' + oCols.find('option:selected').html() + '|' + oOperators.val() + '|' + strValue + '|' + strType + '" />';
	strHtml += '</div>';

	//add the row in...
	if( bFirst ){
		oParent.after(strHtml);
	}
	else{
		$('.filter_condition:last').after(strHtml);
	}

	//make sure we show the filter logic select & the remove all button
	oLogic.show();
	$('#remove_all_filter_button').show();
}

function removeCondition(poLink){

	//if we're removing the first link, change the logic operator of the next to AND (just to be safe), and hide it
	if( $(poLink).attr('id') == $('.remove_condition_link:first').attr('id') && $('.filter_condition').length > 1 ){
		var oNext = $(poLink).parent().next('.filter_condition');
		oNext.find('.filter_logic').remove();
		var strCondition = oNext.find('[@name="customConditions[]"]').val();
		var aCondition = strCondition.split('|');
		oNext.find('[@name="customConditions[]"]').val('AND|' + aCondition[1] + '|' + aCondition[2] + '|' + aCondition[3] + '|' + aCondition[4] + '|' + aCondition[5]);
	}

	//now remove the condition
	$(poLink).parent().remove();

	//hide the filter logic option & the remove all button if there are no more conditions
	if( !$('.filter_condition').length ){


		$('#filter_logic').hide();
		$('#remove_all_filter_button').hide();
	}
}

function removeAllConditions(){
	$('.filter_condition').remove();
	$('[@name="filter_logic"]').hide();
	$('#remove_all_filter_button').hide();
}



