// -------------------------------------------------------------------------------//
// PAGE START FUNCTIONS                                                           //
// -------------------------------------------------------------------------------//
function startpage(section) {	
	checkCookies();
	checkDebug();
	
	if(section != null && section != "lasso" && section != "institution_account") {
		section(); //this will launch the relevant page functions
	}
	
	if (navigator.userAgent.toLowerCase().indexOf('msie 6') > -1) {
		supersleight.run();
	}
	
	if(form = document.getElementsByName('myform')[0]){
		storeData(form, storedData, false);	
	}
	
	if(section == "institution_account"){
		//oneTimeWarning("festivePeriod", "For any student registrations received after the 22nd December, please allow up to ten days for them to be processed. The i-studentenquiry office will be closed over the festive period and will re-open on the 3rd January 2012.\r\n\r\nWe apologise for any inconvenience this may cause\r\n\r\nBest wishes, The i-studentenquiry Team.");
	}
	
	if(window.location.href.indexOf('http://www.i-studentenquiry.com/register_student_personal.php') == 0){
		//oneTimeWarning("festivePeriod", "For any student registrations received after the 22nd December, please allow up to ten days for them to be processed. The i-studentenquiry office will be closed over the festive period and will re-open on the 3rd January 2012.\r\n\r\nWe apologise for any inconvenience this may cause\r\n\r\nBest wishes, The i-studentenquiry Team.");
	}
}

var storedData = new Object();
var newData = new Object();
var dataSaved = false;

function storeData(form, obj, check){
	var elem = form.elements;
	for(var i = 0; i < elem.length; i++) {
		var theName = elem[i].name;
		if(theName != ''){
			if(!obj[theName]){	
				obj[theName] = 'X';
				if(elem[i].type == 'checkbox'){
					obj[theName] = new Array();
				}
			}
			if(elem[i].type == 'checkbox'){
				if(elem[i].checked) {
					obj[theName][obj[theName].length] = elem[i].value;
				}			
			}else if(elem[i].type == 'radio') {			
				if(elem[i].checked) {
					obj[theName] = elem[i].value;
				}
			} else {
				obj[theName] = elem[i].value;
			}
		}
	}	
	if(!check)window.onbeforeunload = checkLoseData;
}

function checkLoseData(){
	var error = false;
	if(!dataSaved){
		if(form = document.getElementsByName('myform')[0]){
			storeData(form, newData, true);	
		}
		
		for(i in newData){
			if(isArray(newData[i])){
				if( storedData[i].length != newData[i].length){
					error = true;					
				} else {
					for(k in newData[i]){			
						if(storedData[i][k] != newData[i][k]){
							error = true;
						}
					}
				}
			} else {				
				if(storedData[i] != newData[i] && i != "accountProfile"){
					error = true;
				}
			}
		}
		
		if(error){
			return "The data on this page has not been saved. Please click cancel and use the page navigation to save your data.";
		}
	}	
}

function isArray(obj) {
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}


// -------------------------------------------------------------------------------//
// GOOGLE ANALYTICS                                                               //
// -------------------------------------------------------------------------------//
if ((TrackingCode == undefined) || (TrackingCode == "")){
	var TrackingCode = "UA-15166699-1";
}

if ((ClientCode == undefined) || (ClientCode == "")){
	var ClientCode = "none";
}

var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
var hndl = window.setTimeout("StartTracking()", 100);

function StartTracking(){
if (typeof(_gat) == 'object')
{
window.clearTimeout(hndl);
	var firstTracker = _gat._getTracker(TrackingCode);
	firstTracker._initData();
	firstTracker._trackPageview();
	if(ClientCode != "none"){
		var secondTracker = _gat._getTracker(ClientCode);
		secondTracker._setDomainName("none");
		secondTracker._setAllowLinker(true);
		secondTracker._initData();
		secondTracker._trackPageview();
	}
} else {
hndl = window.setTimeout("StartTracking()", 1000);
}
}

// -------------------------------------------------------------------------------//
// GOOGLE ANALYTICS - LINK TRACKING                                               //
// -------------------------------------------------------------------------------//
function LinkTracking(address, category, action, label){
	var firstTracker = _gat._getTracker(TrackingCode);
	firstTracker._trackEvent(category, action, label);
	if(ClientCode != "none"){
		var secondTracker = _gat._getTracker(ClientCode);
		secondTracker._trackEvent(category, action, label);
	}
	setTimeout(function(){
		window.open(address.href);
		return false;
	}, 100);
}

// -------------------------------------------------------------------------------//
// BROWSER DETECTION                                                              //
// -------------------------------------------------------------------------------//
function browserDetection() {
	var BrowserDetect = {
		init: function () {
			this.browser = this.searchString(this.dataBrowser) || "Unknown";
			this.version = this.searchVersion(navigator.userAgent)
				|| this.searchVersion(navigator.appVersion)
				|| "0";
			this.OS = this.searchString(this.dataOS) || "Unknown";
		},
		searchString: function (data) {
			for (var i=0;i<data.length;i++)	{
				var dataString = data[i].string;
				var dataProp = data[i].prop;
				this.versionSearchString = data[i].versionSearch || data[i].identity;
				if (dataString) {
					if (dataString.indexOf(data[i].subString) != -1)
						return data[i].identity;
				}
				else if (dataProp)
					return data[i].identity;
			}
		},
		searchVersion: function (dataString) {
			var index = dataString.indexOf(this.versionSearchString);
			if (index == -1) return;
			return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
		},
		dataBrowser: [
			{string: navigator.userAgent, subString: "Chrome", identity: "Chrome"},
			{string: navigator.userAgent, subString: "Dreamweaver", identity: "Dreamweaver"},
			{string: navigator.userAgent, subString: "OmniWeb",	versionSearch: "OmniWeb/", identity: "OmniWeb"},
			{string: navigator.userAgent, subString: "LittleSnapper", identity: "LittleSnapper"},
			{string: navigator.vendor, subString: "Apple", identity: "Safari", versionSearch: "Version"},
			{prop: window.opera, identity: "Opera"},
			{string: navigator.vendor, subString: "iCab", identity: "iCab"},
			{string: navigator.vendor, subString: "KDE", identity: "Konqueror"},
			{string: navigator.vendor, subString: "Camino", identity: "Camino"},
			{string: navigator.userAgent, subString: "Firefox", identity: "Firefox"},
			// for newer Netscapes (6+)
			{string: navigator.userAgent, subString: "Netscape", identity: "Netscape"},
			{string: navigator.userAgent, subString: "MSIE", identity: "Explorer", versionSearch: "MSIE"},
			{string: navigator.userAgent, subString: "Gecko", identity: "Mozilla", versionSearch: "rv"},
			// for older Netscapes (4-)
			{string: navigator.userAgent, subString: "Mozilla", identity: "Netscape", versionSearch: "Mozilla"}
		],
		dataOS : [
			{string: navigator.platform, subString: "Win", identity: "Windows"},
			{string: navigator.platform, subString: "Mac", identity: "Mac"},
			{string: navigator.userAgent, subString: "iPhone", identity: "iPhone/iPod"},
			{string: navigator.platform, subString: "Linux", identity: "Linux"}
		]
	};
	BrowserDetect.init();

	//Increments by one on every occurance where the browser being used is not in the list of working browsers
	var redirectCount = 0;
	
	//An array containing all the working browsers
	var browsers = new Array('Firefox','Explorer','Opera','Safari','LittleSnapper','Dreamweaver','Chrome') ;
	var browserlowest = new Array('3','7','9.6','5','1','11','6') ;

	//For loop goes through the array and adds one to the counter everytime the browsers is not equal to the current array item
	for (i=0; i < browsers.length; i++) {
		if (BrowserDetect.browser != browsers[i]) {
			redirectCount++;
		} else if (BrowserDetect.version < browserlowest[i]) {
			//window.location = 'http://www.i-studentenquiry.com/alert/english/website.html';
		}
	}
	
	//If the counter is not equal to the lenght of the array it means the browser being use is not permitted and will redirect
	if (redirectCount == browsers.length) {
		//window.location = 'http://www.i-studentenquiry.com/alert/english/website.html';
	}
}

// -------------------------------------------------------------------------------//
// COOKIE FUNCTIONS                                                               //
// -------------------------------------------------------------------------------//
function checkCookies(c_name) {
	debugMode = getCookie('debugMode');
	browserForced = getCookie('forceBrowser');
	if ((debugMode != "true") && (browserForced != "true")) {
		browserDetection();
 	}
	if(window.location.href.indexOf('institution_account.php') > -1){
		institutionAccountView = getCookie('institutionAccountView');
		if(institutionAccountView != null){
			var views = institutionAccountView.split('*');
			
			var secs = new Array();			
			var divs = document.getElementsByTagName('div');
			for(i=0; i<divs.length; i++){
				if(divs[i].className == 'accountSection'){
					secs.push(divs[i]);	
				}
			}
			
			for(j=0; j<secs.length; j++){
				if(views[j] == 'block'){
					showSection(secs[j].id,j);	
				}
			}
		}
	}
	if(window.location.href.indexOf('institution_matches.php') > -1){
		recallFields('fieldNames[]');
	}
}

function getCookie(c_name) {
	var nameEQ = c_name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) {
			return c.substring(nameEQ.length,c.length);
		}
    }
    return null;
	
}

function setCookie(c_name,value,expiry) {
	var exdate=new Date();
	var path="/";
	exdate.setDate(exdate.getDate()+expiry);
	
	document.cookie=c_name+"="+escape(value)+((expiry=="")?";expires="+exdate.toGMTString():"")+((path)?";path="+path:"");
}

// -------------------------------------------------------------------------------//
// DEBUG MODE FUNCTIONS                                                           //
// -------------------------------------------------------------------------------//
function checkDebug() {
	if (document.location.href.indexOf('enableDebug') > -1) {
		enableDebug();
	} else if (document.location.href.indexOf('disableDebug') > -1) {
		disableDebug();
	}
}

function enableDebug() {
	setCookie('debugMode','true',1);
	alert("DEBUG ENABLED");
}

function disableDebug() {
	setCookie('debugMode','false',-1);
	alert("DEBUG DISABLED");
}

// -------------------------------------------------------------------------------//
// FORCE BROWSER FUNCTIONS                                                        //
// -------------------------------------------------------------------------------//
function forceBrowser() {
	setCookie('forceBrowser','true');
	var referrer = unescape(getCookie('referrerAddress'));
	if (referrer.indexOf('www.') < 0) {
		referrer = referrer.split('http://');
		referrer = "http://www."+referrer[1];
	}
	window.location = referrer;
}

// -------------------------------------------------------------------------------//
// PNG TRANSPARENCY                                                               //
// -------------------------------------------------------------------------------//
var supersleight	= function() {	
	var root = false;
	var applyPositioning = true;
	
	// Path to a transparent GIF image
	var shim			= 'includes/javascript/clear.gif';
	
	// RegExp to match above GIF image name
	var shim_pattern	= /includes\/javascript\/clear\.gif$/i;	
	
	var fnLoadPngs = function() { 
		if (root) {
			root = document.getElementById(root);
		}else{
			root = document;
		}
		for (var i = root.all.length - 1, obj = null; (obj = root.all[i]); i--) {
			// background pngs
			if (obj.currentStyle.backgroundImage.match(/\.png/i) !== null) {
				bg_fnFixPng(obj);
			}
			// image elements
			if (obj.tagName=='IMG' && obj.src.match(/\.png$/i) !== null){
				el_fnFixPng(obj);
			}
			// apply position to 'active' elements
			if (applyPositioning && (obj.tagName=='A' || obj.tagName=='INPUT') && obj.style.position === ''){
				obj.style.position = 'relative';
			}
		}
	};

	var bg_fnFixPng = function(obj) {
		var mode = 'scale';
		var bg	= obj.currentStyle.backgroundImage;
		var src = bg.substring(5,bg.length-2);
		if (obj.currentStyle.backgroundRepeat == 'no-repeat') {
			mode = 'crop';
		}
		obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + mode + "')";
		obj.style.backgroundImage = 'url('+shim+')';
	};

	var el_fnFixPng = function(img) {
		var src = img.src;
		var objClass = img.className;
		if(objClass.indexOf('hiddenElement') > -1){
			var tmpImg = new Image();
			tmpImg.src = img.src;			
			img.style.width = tmpImg.width + "px";
			img.style.height = tmpImg.height + "px";
			delete tmpImg;
		} else {
			img.style.width = img.width + "px";
			img.style.height = img.height + "px";
		}
		
		img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')";
		img.src = shim;
	};
	
	var addLoadEvent = function(func) {
		var oldonload = window.onload;
		if (typeof window.onload != 'function') {
			window.onload = func;
		} else {
			window.onload = function() {
				if (oldonload) {
					oldonload();
				}
				func();
			};
		}
	};
	
	return {
		init: function() { 
			addLoadEvent(fnLoadPngs);
		},
		
		limitTo: function(el) {
			root = el;
		},
		
		run: function() {
			fnLoadPngs();
		}
	};
}();

// -------------------------------------------------------------------------------//
// READ MORE TOGGLE                                                               //
// -------------------------------------------------------------------------------//
function readmore(obj, objlink) {
	var readmore = document.getElementById(obj);
	var readmorelink = document.getElementById(objlink);
	if (readmore != null) {
		if (readmore.style.display != 'none') {
			readmore.style.display = 'none';
			readmorelink.innerHTML = 'click here';
		}
		else {
			readmore.style.display = 'block';
			readmorelink.innerHTML = 'click here (hide)';
		}
	}
}

// -------------------------------------------------------------------------------//
// MORE INFO                                                                      //
// -------------------------------------------------------------------------------//
function moreinfo(){
	readmore('readmore1','readmore1-link');
}

// -------------------------------------------------------------------------------//
// PAGE REDIRECT                                                                  //
// -------------------------------------------------------------------------------//
function pageRedirect(address){
	window.location = address;
}

// -------------------------------------------------------------------------------//
// TOOL TIP FUNCTION                                                              //
// -------------------------------------------------------------------------------//
var tooltip=function(){
	var id = 'tt';
	var top = 12;
	var left = 3;
	var maxw = 300;
	var speed = 10;
	var timer = 20;
	var endalpha = 90;
	var alpha = 0;
	var tt,t,c,b,h;
	var ie = document.all ? true : false;
	return{
		show:function(v,w){
			if(tt == null){
				tt = document.createElement('div');
				tt.setAttribute('id',id);
				t = document.createElement('div');
				t.setAttribute('id',id + 'top');
				c = document.createElement('div');
				c.setAttribute('id',id + 'cont');
				b = document.createElement('div');
				b.setAttribute('id',id + 'bot');
				tt.appendChild(t);
				tt.appendChild(c);
				tt.appendChild(b);
				document.body.appendChild(tt);
				tt.style.opacity = 0;
				tt.style.filter = 'alpha(opacity=0)';
				document.onmousemove = this.pos;
			}
			tt.style.display = 'block';
			c.innerHTML = v;
			tt.style.width = w ? w + 'px' : 'auto';
			if(!w && ie){
				t.style.display = 'none';
				b.style.display = 'none';
				tt.style.width = tt.offsetWidth;
				t.style.display = 'block';
				b.style.display = 'block';
			}
			if(tt.offsetWidth > maxw){tt.style.width = maxw + 'px'}
			h = parseInt(tt.offsetHeight) + top;
			clearInterval(tt.timer);
			tt.timer = setInterval(function(){tooltip.fade(1)},timer);
		},
		pos:function(e){
			var u = ie ? event.clientY + document.documentElement.scrollTop : e.pageY;
			var l = ie ? event.clientX + document.documentElement.scrollLeft : e.pageX;
			tt.style.top = (u + top) + 'px';
			tt.style.left = (l + left) + 'px';
		},
		fade:function(d){
			var a = alpha;
			if((a != endalpha && d == 1) || (a != 0 && d == -1)){
				var i = speed;
				if(endalpha - a < speed && d == 1){
					i = endalpha - a;
				}else if(alpha < speed && d == -1){
					i = a;
				}
				alpha = a + (i * d);
				tt.style.opacity = alpha * .01;
				tt.style.filter = 'alpha(opacity=' + alpha + ')';
			}else{
				clearInterval(tt.timer);
				if(d == -1){tt.style.display = 'none'}
			}
		},
		hide:function(){
			clearInterval(tt.timer);
			tt.timer = setInterval(function(){tooltip.fade(-1)},timer);
		}
	};
}();

// -------------------------------------------------------------------------------//
// LAUNCHES POPUP WINDOWS IN FULL SCREEN WITH SCROLLBARS                          //
// -------------------------------------------------------------------------------//
function fullscreen(url,name,saveWindow) {
	if (window.name != "undergraduate" && window.name != "postgraduate" && window.name != "esl") {
		var nw = window.open(url,name,'width='+screen.availWidth+',height='+screen.availHeight+',scrollbars=1,location=0,status=0,toolbar=0,menubar=0,top=0, left=0');
	} else {
		window.location.href = url;
	}
}

// -------------------------------------------------------------------------------//
// LIMIT TEXTAREA CHARACTERS							                          //
// -------------------------------------------------------------------------------//
function ismaxlength(obj) {
	var mlength = obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : "";
	if (obj.getAttribute && obj.value.length>mlength) {
		obj.value=obj.value.substring(0,mlength);
	}
}

// -------------------------------------------------------------------------------//
// BACK BUTTON GENERATOR                                                          //
// -------------------------------------------------------------------------------//
function backButton() {
	var saved = getCookie('enquiryLocation');
	var admin = getCookie('isep_admin');
	
	if ((saved != null) && (admin == null)) {
		var holder = document.createElement('div');
		holder.setAttribute('id','backbutton');
		document.body.appendChild(holder);
		var button = document.getElementById('backbutton');
		button.innerHTML = "<a href='"+document.location.protocol+"//"+document.domain+saved+"'>BACK TO REGISTRATION FORM</a>";
	}
}	

// -------------------------------------------------------------------------------//
// SELECT/DESELECT ALL LIST                                                       //
// -------------------------------------------------------------------------------//
function asmDeselectAll(listID){
	$("#"+listID).children().attr("selected", "").end().change();
	return false;		
}
	
function asmSelectAll(listID){
	$("#"+listID).children().attr("selected", "selected").end().change();
	return false;		
}	

function checkAll(name){
	var cbs = document.getElementsByName(name);
	
	for(i=0; i<cbs.length; i++){
		cbs[i].checked = true;	
	}
}

function uncheckAll(name){
	var cbs = document.getElementsByName(name);
	
	for(i=0; i<cbs.length; i++){
		cbs[i].checked = false;	
	}	
}
// -------------------------------------------------------------------------------//
// ADAMS FUNCTIONS                                                                //
// -------------------------------------------------------------------------------//
function showHideList(subjectarea){
	for(i=1; i<=8; i++){
		if(i != 7){
			list = document.getElementById("subjectArea"+i);
			arrow = document.getElementById("arrowSA"+i);
			if(subjectarea == i){
				if(list.style.display == ''){
					arrow.src = 'includes/images/arrow-down.png';
					list.style.display = 'block';
				} else {
					arrow.src = 'includes/images/arrow-side.png';
					list.style.display = '';
				}
			} else {
				arrow.src = 'includes/images/arrow-side.png';
				list.style.display = '';
			}
		}
	}
}

function onSubjectChecked(obj){
	var SA = obj.parentNode.parentNode.id.replace("subjectArea",'');
	if(obj.checked){
		updateSubjectCount(SA, 1);
	} else {
		updateSubjectCount(SA, -1);
	}
}	

function subjectCheckAll(name){
	var cbs = document.getElementsByName(name);
	var SA = name.substring(2,3);
	
	for(i=0; i<cbs.length; i++){
		if(cbs[i].checked == false)updateSubjectCount(SA, 1);
		cbs[i].checked = true;	
	}
}

function subjectUncheckAll(name){
	var cbs = document.getElementsByName(name);
	var SA = name.substring(2,3);
	
	for(i=0; i<cbs.length; i++){
		if(cbs[i].checked == true)updateSubjectCount(SA, -1);
		cbs[i].checked = false;	
	}
}

function searchSubjectChosen(){
	var searchterm = document.getElementById('suggestSubjects');
	var subjectFound = false;
	
	for(i=0; i< subjectCheckBoxes.length; i++){
		if(subjectCheckBoxes[i].value == searchterm.value){
			if(!subjectCheckBoxes[i].checked){
				$("#subjectChosenMessage").css("display","inline").delay(800).fadeOut(400);
				subjectCheckBoxes[i].checked = true;
				onSubjectChecked(subjectCheckBoxes[i]);	
				subjectFound = true;			
			}
			searchterm.value = '';
			break;	
		} 
	}
	
/*	if(!subjectFound) {
		document.getElementById('subjectsOther').value += searchterm.value+", ";
		searchterm.value = '';
		if(document.getElementById('subjectArea8').style.display == '' || document.getElementById('subjectArea8').style.display == 'none'){
			showHideList(8);
		}
	}*/
}

function updateSubjectCount(SA, inc){
	subjectCount['SA'+SA] += inc;
	var countText = document.getElementById('SAcount'+SA);
	if(subjectCount['SA'+SA] != 0){
		countText.innerHTML = '('+subjectCount['SA'+SA]+')';
	} else {
		countText.innerHTML = '';
	}
}

function reviewAndSubmit(){
	dataSaved = true;
	var form = document.getElementsByName('myform')[0];
	if(form.action.indexOf('?') > -1){
		form.action += '&review=true';
	} else {
		form.action += '?review=true';
	}
	form.submit();
}

function previousPage(skip) {
	dataSaved = true;	
	if(skip){
		document.myform.action='includes/php/actions/previousPage.php';
	} else {
		document.myform.action+='?previous=true';			
	}
	document.myform.submit()
}

function nextPage() {
	dataSaved = true;	
	document.myform.submit()
}

function requiredDataMissing(name, redirect) {
	dataSaved = true;
	var form = document.getElementsByName(name)[0];
	form.action='includes/php/actions/requiredDataMissing.php?redirect='+redirect;
	form.submit()
}

function accountSwap() {
	var btns = document.getElementsByClassName('showHide');
	for(i=0; i<btns.length; i++){
		$(btns[i]).attr('onClick');
	}
	
	var gc = getCookie('currentGradLvl');
	if(gc == null) gc = document.getElementById('accountProfile').value;
	setCookie('prevGradLvl', gc);
	setCookie('currentGradLvl',document.getElementById('accountProfile').value);
	
	window.location.search = '?showForm='+document.getElementById('accountProfile').value;
}

function saveEdit(process){
	dataSaved = true;
	var form = document.getElementsByName('myform')[0];
	form.action = process+'?edit=true';
	ds = skipSave == undefined ? '&dontsave=true' : false;
	if(ds != false){
		form.action += ds;
	}
	form.submit();
}

function resendConfirmation(gradLvl){
	window.location = 'includes/php/actions/resendConfirmation.php?ref='+window.location.pathname+'&showForm='+gradLvl;
}

function changePassword(){
	var currentPassRow = document.getElementById("currentPassRow");
	var newPassRow = document.getElementById("newPassRow");
	var confirmPassRow = document.getElementById("confirmPassRow");
	var passMessage = document.getElementById("passMessage");
	var passSubmit = document.getElementById("passSubmit");
	newPassRow.style.display = '';
	currentPassRow.style.display = '';
	confirmPassRow.style.display = '';
	passMessage.style.display = '';
	passSubmit.style.display = '';
}

function deleteAccount(id, usertype){
	window.location = 'includes/php/actions/admin/deleteAccount.php?ref=deleteAccounts.php&id='+id+'&type='+usertype;	
}

function bubbleNavigation(toPage){
	var form = document.getElementsByName('myform')[0];
	form.action = "includes/php/actions/shortcut.php?to="+toPage;
	dataSaved = true;
	form.submit();
}

function saveSubmit(){
	dataSaved = true;
	var form = document.getElementsByName('myform')[0];
	form.submit();
		
}

function showStudentMatchDetails(id){
	var sd = document.getElementById('studentMatchDetails'+id);
	var arrow = document.getElementById('arrow'+id);
	if(sd.style.display == 'table-row'){
		sd.style.display = '';	
		arrow.src = 'includes/images/arrow-side.png';
	} else {
		sd.style.display = 'table-row';	
		arrow.src = 'includes/images/arrow-down.png';
	}
}

function showUniMatchDetails(id){
	var sd = document.getElementById('uniMatchDetails'+id);
	var arrow = document.getElementById('arrow'+id);
	if(sd.style.display == 'block'){
		sd.style.display = '';	
		arrow.src = 'includes/images/arrow-side.png';
	} else {
		sd.style.display = 'block';	
		arrow.src = 'includes/images/arrow-down.png';
	}
}

function checkAddToSS(form){
	var inputs = document[form].getElementsByTagName('input');		
	var error = 0;
	var cbs = new Array();
	for(i=0; i<inputs.length; i++){
		if(inputs[i].type == 'checkbox' && inputs[i].name == 'studentIDs[]'){
			cbs.push(inputs[i]);
			if(!inputs[i].checked){
				error++;
			}
		}
	}
	
	if(cbs.length == error){
		alert('You must select at least one student to generate the spreadsheet');
		return false;	
	}
	return true;
}

// SHADOWBOX
function showShadowBox(sb, page){
	$("#overlay").fadeIn().click(function() {  
		$(this).fadeOut();
		$("#"+sb).fadeOut(400, function(){
			for(i=0; i<currentShadowBox.pages.length; i++){
				if(i== currentShadowBox.current){
					currentShadowBox.pages[i].style.display = 'none';
				}
			}			
		});
	});;
	
	if(currentShadowBox == undefined){
		document.currentShadowBox = new Object();	
	}
	currentShadowBox.box = document.getElementById(sb);
	currentShadowBox.form = document.getElementById(sb).parentNode;
	tmpPages = document.getElementById(sb).getElementsByTagName("div");
	var arr = new Array();
	for(i=0; i<tmpPages.length; i++){
		if(tmpPages[i].className != 'control' && tmpPages[i].className != null){
			arr.push(tmpPages[i]);
		}
	}
	
	currentShadowBox.pages = arr;
	
	for(i=0; i<currentShadowBox.pages.length; i++){
		if(i == page){
			currentShadowBox.current = page;
			$(currentShadowBox.pages[i]).fadeIn();
		}
	}
	
	$("#"+sb).fadeIn();
	$("#"+sb).css({"margin-top":"-300px", "margin-left":"-330px"});	
}

function shadowBoxNextPage(){
	var passed = true;
	var count = 0;
	var errorRadio = 0;
	var errorCheckBox = 0;
	
	var inputs = currentShadowBox.pages[currentShadowBox.current].getElementsByTagName("input");
	for(i=0; i<inputs.length; i++){
		if(inputs[i].type == "radio"){
			count++;
			if(!inputs[i].checked){
				errorRadio++;	
			}
		} else if(inputs[i].type == "checkbox"){
			count++;
			if(!inputs[i].checked){
				errorCheckBox++;	
			}			
		}
	}
	if(errorRadio == count) passed = false;
	if(errorCheckBox == count) passed = false;
	
	if(passed){
		for(i=0; i<currentShadowBox.pages.length; i++){
			if(i == currentShadowBox.current){
				if(i+1 < currentShadowBox.pages.length){
					$(currentShadowBox.pages[currentShadowBox.current]).fadeOut(400, function(){
						currentShadowBox.current = parseInt(i)+1;	
						$(currentShadowBox.pages[currentShadowBox.current]).fadeIn();
					});		
					break;
				} else {
					document.getElementById('finalbtn').style.display = "block";					
					for(i=0; i<currentShadowBox.pages.length; i++){
						if(i== currentShadowBox.current){
							$(currentShadowBox.pages[i]).fadeOut();
						}
					}	
					saveFields('fieldNames[]');
					currentShadowBox.form.submit();
					break;
				}
			}
		}
	} else {
		if (errorRadio == count) {
			alert('You must select a format before continuing.');
		} else if (errorCheckBox == count) {
			alert('You must check at least one box before continuing.');
		}
	}
}

function shadowBoxPreviousPage(){
	for(i=0; i<currentShadowBox.pages.length; i++){
		if(i == currentShadowBox.current){
			if(i-1 >= 0){
				$(currentShadowBox.pages[currentShadowBox.current]).fadeOut(400, function(){
					currentShadowBox.current = parseInt(i)-1;	
					$(currentShadowBox.pages[currentShadowBox.current]).fadeIn();
				});		
				break;
			}
		}
	}
}

function shadowBoxSelectAll(checked){
	var inputs = currentShadowBox.pages[currentShadowBox.current].getElementsByTagName("input");

	for(i=0; i<inputs.length; i++){
		if(inputs[i].type == "checkbox"){
			inputs[i].checked = checked;
		}
	}
}

// END SHADOW BOX

function closeRefresh(){
	window.location = "../../../institution_matches.php";	
}

var currentShadowBox = new Object();

function showSection(id, num){
	var div = document.getElementById(id);
	var text = '';
	if(div.style.display == 'block'){
		div.style.display = '';
		text = 'Show';
	} else {
		div.style.display = 'block';		
		text = 'Hide';
	}
	
	var inps = document.getElementsByTagName('input');
	var btns = new Array();
	for(i in inps){
		if(inps[i].className == 'showHide'){
			btns.push(inps[i]);	
		}
	}
	
	for(i=0; i<btns.length; i++){
		if(i == num){
			btns[i].value = text;
		}
	}
	
	var views = '';
	
	var divs = document.getElementsByTagName('div');
	var secs = new Array();
	for(i in divs){
		if(divs[i].className == 'accountSection'){
			secs.push(divs[i]);	
		}
	}
	
	for(i=0; i<secs.length; i++){
		views += secs[i].style.display+'*';
	}
	
	views = views.substring(0, views.length-1);
	setCookie('institutionAccountView',views);
}

function recallFields(cbName){		
	var fieldString = getCookie(cbName+"Cookie");

	var fields = document.getElementsByName(cbName);
	for(i in fields) {
		if(fieldString.charAt(i) == "1") {
			fields[i].checked = true;
		} else {
			fields[i].checked = false;
		}
	}
}

function saveFields(cbName){
	var saveString = "";
	
	var fields = document.getElementsByName(cbName);
	for(i in fields) {
		if(fields[i].checked){
			saveString += "1";	
		} else {
			saveString += "0";	
		}
	}
	
	setCookie(cbName+"Cookie",saveString);
}


function matchesSelectAll(form){
	var inputs = document[form].getElementsByTagName('input');
	
	for(i=0; i<inputs.length;i++){
		if(inputs[i].type == 'checkbox'){
			inputs[i].checked = true;	
		}
	}
}

function matchesDeselectAll(form){
	var inputs = document[form].getElementsByTagName('input');
	
	for(i=0; i<inputs.length;i++){
		if(inputs[i].type == 'checkbox'){
			inputs[i].checked = false;	
		}
	}
}

function matchesSelectNew(form){
	var inputs = document[form].getElementsByTagName('input');
	
	for(i=0; i<inputs.length;i++){
		if(inputs[i].type == 'checkbox'){
			if(inputs[i].parentNode.nextSibling.innerHTML == ""){
				inputs[i].checked = true;	
			}
		}
	}
}

function oneTimeWarning(name, warning){
	var cookieVal = getCookie(name+'Warning');
	if(cookieVal == null){
		alert(warning);
		setCookie(name+'Warning','true',1);
	}
}
