
// global context, baby!
var activityId = 1;
var userId = 5;
var primaryInfo;
var documentInfo;


/*Date picker*/
$(function() {
	// set the default expected data type returned from all ajax calls to JSON
	$.ajaxSetup({
		dataType:'json',
		accepts:{json:'application/json'}
	});
	
	var urlvars = getUrlVars();
	requestId = parseInt(urlvars['rid'], 10);	//id == activityId, rid == requestId
	var requestIdMap = {"requestId":requestId};
	var userIdMap = {"userId":userId};
	
	//dirty form
	$.fn.checkChanges = function(message) {

		var _self = this;

		$(_self).bind('keyup change keydown', function(e) {
			$(this).addClass('changedInput');
		});

		$(window).bind('beforeunload ', function() {
			if ($('.changedInput').length) {
				return message;
			}
		});

	};
	
	//Timer to look for the scroll bar and add visual indicator of scrollable content
	var timer = setInterval(function() {checkForScollbar();}, 50);
	
	//$('input').checkChanges('You have made changes on this page that you have not yet confirmed. If you navigate away from this page you will lose those changes.');
	//end dirty form check
});

// Gets whether or not the scroll bar for the given element exists
// Returns boolean
function getScrollbar(window) {
	var document = window.document, c = document.compatMode;
    r = c && /CSS/.test(c) ? document.documentElement : document.body;
    if (typeof window.innerWidth == 'number') {
    	return [ window.innerHeight > r.clientHeight, window.innerWidth > r.clientWidth ];
    } else {
    	return [ r.scrollWidth > r.clientWidth, r.scrollHeight > r.clientHeight ];
    }
}

// Adds the scroll indicator to the DOM if needed
function checkForScollbar() {
	
	var atBottom = $(window).scrollTop() + $(window).height() >= $(document).height(),
		scrollBar = getScrollbar(window)[1];
	
	if (scrollBar && !$('#scrollIndicator').get(0) && !atBottom) {
		$('body').prepend('<div id="scrollIndicator">&nbsp;</div>');
	} else if ((!scrollBar || atBottom) && $('#scrollIndicator').get(0)) {
		$('#scrollIndicator').remove();
	}
}

onload = function() {
	a_tags=document.getElementsByTagName('a');
	for (i=0;i<a_tags.length;i++) {
		a_tags[i].onfocus=blur_links;
	}
};

function blur_links() {
	this.blur()
}

//Read a page's GET URL variables and return them as an associative array.
getUrlVars = function()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

$('#dashboard a:first').tab('show'); // Select first tab
$('#dashboard a:last').tab('show'); // Select last tab


//Upload button & field	 
	 $('#fileselectbutton').click(function(e){
	  $('#file').trigger('click');
	 });
	    
	 $('#file').change(function(e){
	  var val = $(this).val();
	   
	  var file = val.split(/[\\/]/);
	   
	  $('#filename').val(file[file.length-1]);
	 });
	 
//preloader
var progressIncrease = function(pct){
	$('#preload .bar').css('width',pct);
}


//reset the document upload element (could be used to reset other elements)
function reset( element ) {
	if(element != null && element != undefined) {
		element.wrap('<form>').closest('form').get(0).reset();
    	element.unwrap();
	}//end if
}//end reset​


//on expand/collapse, update the caret icon
var initExpandCollapseIconActions = function() {
	
	$('.accordion-body').on('show', function () {	//expand
		var collapseId = $(this).attr("id");
		//alert("show:  " + collapseId);
		
		$('a[href="#'+collapseId+'"]').find('i.icon-caret-right').removeClass('icon-caret-right').addClass('icon-caret-down');	//show the down caret icon
	});

	$('.accordion-body').on('hide', function () {	//collapse
		var collapseId = $(this).attr("id");
		//alert("hide:  " + collapseId);
		
		$('a[href="#'+collapseId+'"]').find('i.icon-caret-down').removeClass('icon-caret-down').addClass('icon-caret-right');	//show the right caret icon					
	});
	
};


//on expand/collapse, update the caret icon
var initExpandCollapseIconNoteActions = function() {
	
	$('.accordion-bodynote').on('show', function (event) {	//expand
		event.stopPropagation();
		var collapseId = $(this).attr("id");
		//alert("show:  " + collapseId);
		
		$('a[href="#'+collapseId+'"]').find('i.icon-caretnote-right').removeClass('icon-caretnote-right').addClass('icon-caretnote-down');	//show the down caret icon
	});

	$('.accordion-bodynote').on('hide', function (event) {	//collapse
		event.stopPropagation();
		var collapseId = $(this).attr("id");
		//alert("hide:  " + collapseId);
		
		$('a[href="#'+collapseId+'"]').find('i.icon-caretnote-down').removeClass('icon-caretnote-down').addClass('icon-caretnote-right');	//show the right caret icon					
	});
	
};


var focusable = 'input,select,textarea,button,a[role="button"],.chzn-default';

if($("#wizard").length>0){
    $("#wizard").bwizard({
    	validating: function (e, ui) {
    		wizardValidating(e, ui);
    	},
    	show: function (e, ui) {
    		refocusWizard();

    		//508: auto-focus first element in current panel
    		$(ui.panel).find(focusable).first().focus();

    		//in case the next button is really low on the screen
    		$('body').animate({ scrollTop: '0' }, 'fast');
    	}
    });
	//508: auto-focus first element in the wizard
	$("#wizard .bwizard-activated").find(focusable).first().focus();
}

refocusWizard = function(){
    //508: remove focus from everything
	$("#wizard div.hide").find(focusable).each(function(){
		$(this).attr('tabindex','-1');
	});
	//508: add focus to first panel in wizard
	$("#wizard .bwizard-activated").find(focusable).each(function(){
		$(this).attr('tabindex','0')
	});
}

//remove the hash from the window location
function removeHash() {

	var scrollV, scrollH;

	if ("pushState" in history) {

		history.pushState("", document.title, window.location.pathname + window.location.search);
//		history.pushState("", document.title, window.location.pathname);

	} else {

		// Prevent scrolling by storing the page's current scroll offset
		scrollV = document.body.scrollTop;
		scrollH = document.body.scrollLeft;

		window.location.hash = "";

		// Restore the scroll offset, should be flicker free
		document.body.scrollTop = scrollV;
		document.body.scrollLeft = scrollH;
	}
}

//show/hide the Data Source server location controls
function showServerLocation( showLoc ) {
	
	if( showLoc ) {
		$("#serverLocation").slideDown()
	} else {
		$("#serverLocation").slideUp();
	}
}

//moved to create-non-research-request.js because create-new-request.html now uses checkboxes instead of radio buttons
///*Data Location*/
//jQuery(function(){
//        jQuery("input[name=dataLocation]").change(function(){          
//            
//            
//            if ($(this).val() == "localServerLocation") {
//            jQuery("#serverLocation").slideDown()
//            }
//            else {
//            jQuery("#serverLocation").slideUp();
//            }                                                            
//       });
//});

//show/hide the Data Source server location controls
function showTransferredExternalDestination( showDest ) {

    if( showDest ) {
        $("#transferredExternalDestination").slideDown()
    } else {
        $("#transferredExternalDestination").slideUp();
    }
}

/* Transferred External */
jQuery(function(){
    jQuery("input[name=transferredExternal]").change(function(){

        if ($(this).val() == "transferredExternalYes") {
            jQuery("#transferredExternalDestination").slideDown();
        } else {
            jQuery("#transferredExternalDestination").slideUp();
        }
    });
});

////TODO: doesn't necessarily line up to the latest version?
////
////remember the change request/deny actions
//updateChildActions = function() 
//{
////TODO: maybe pass an action parameter so that if the page is moved, we remember if we were doing a change request or a deny?
//	changeOpen = false;
//	denyOpen = false;
//	
//	//alert("cleared out the child actions: " + changeOpen + ", " + denyOpen);
//}
//
//update = function() 
//{
////TODO: might want to move these to app.js so that it's in one spot (and no matter where they are in the app, we should have the same copy)
////TODO: append the action type to the dashboard URL (display a message)
//	updateChildActions();
//	
//	window.location = "../dashboard.html";
//}