/**
 * function to redirect to a page for the content distribution area
 */
function goToContentPage(type, mainName){
	document.location.href = '/qs/content_main/main-information-page/?product='+ type + '&header=' + mainName;
}

/**
 * main function that returns content to receiving areas
 * @param pane content area
 * @param module
 * @param controller
 * @param action
 * @param arguments
 */
function getContent(pane, module, controller, action, args){

	var myCp= dijit.byId(pane);
	myCp.attr("onDownloadEnd", function(){
	  console.log("Download complete!");
	});
	myCp.attr("href", "/internal/index/");

        
}

/**
 * main function that updates data by callback
 * @param pane content area
 * @param module
 * @param controller
 * @param action
 * @param arguments
 */
function updateData(module, controller, action, args){
		if(!args){args = []}
		//Look up the node we'll stick the text under.
        //var targetNode = dojo.byId(pane + '-ContentPane');
		
		//build the url we are getting data for
        var url = '/' + module + '/' + controller + '/' + action + '/?' + args.join('&');
        //The parameters to pass to xhrGet, the url, how to handle it, and the callbacks.
        var xhrArgs = {
            url: url, 
            handleAs: "text",
            preventCache: false
        }

        //Call the asynchronous xhrGet
        var deferred = dojo.xhrGet(xhrArgs);      
}


/**
 * main function that updates data by callback
 * @param pane content area
 * @param module
 * @param controller
 * @param action
 * @param arguments
 */
function updateDataPostSuccessStory(module, controller, action, arg){
		//Look up the node we'll stick the text under.
        //var targetNode = dojo.byId(pane + '-ContentPane');
		
		//build the url we are getting data for
        var url = '/' + module + '/' + controller + '/' + action + '/';
        //The parameters to pass to xhrGet, the url, how to handle it, and the callbacks.
        var xhrArgs = {
            url: url, 
            postData: arg,
            handleAs: "text",
            preventCache: false
        }

        //Call the asynchronous xhrGet
        var deferred = dojo.xhrPost(xhrArgs); 
        document.location.href = '/internal/setup/success-management/';
}

function updateSuccessStory(arg){
	document.getElementById('successStory').value = arg;
	dijit.byId('addSuccessForm').submit();
}

function updateInlineFormProductionList(id, type, field, value, form){
	document.getElementById('type').value = type;
	document.getElementById('field').value = field;
	document.getElementById('value').value = value;
	document.getElementById('keyID').value = id;
	var xhrArgs = {
            form: dojo.byId(form),
            handleAs: "text"
        }
        //Call the asynchronous xhrPost
        var deferred = dojo.xhrPost(xhrArgs);
}

function updateInlineForm(type, field, value, form){
	document.getElementById('type').value = type;
	document.getElementById('field').value = field;
	document.getElementById('value').value = value;
	var xhrArgs = {
            form: dojo.byId(form),
            handleAs: "text"
        }
        //Call the asynchronous xhrPost
        var deferred = dojo.xhrPost(xhrArgs);
}

function updateInlineFormPlusId(type, field, value, keyID, form){
	document.getElementById('type').value = type;
	document.getElementById('field').value = field;
	document.getElementById('value').value = value;
	document.getElementById('keyID').value = keyID;
	var xhrArgs = {
            form: dojo.byId(form),
            handleAs: "text"
        }
        //Call the asynchronous xhrPost
        var deferred = dojo.xhrPost(xhrArgs);
}

function updateInlineFormSuccess(type, field, value, keyID, form){
	document.getElementById('typeSuccess').value = type;
	document.getElementById('fieldSuccess').value = field;
	document.getElementById('valueSuccess').value = value;
	document.getElementById('keyID').value = keyID;
	var xhrArgs = {
            form: dojo.byId(form),
            handleAs: "text"
        }
        //Call the asynchronous xhrPost
        var deferred = dojo.xhrPost(xhrArgs);
}

function updateInlineAddCandidateNote(value){
	document.getElementById('noteText').value = value;
	dijit.byId('addInlineFieldsAddNoteForm').submit();
}

function updateInlineUpdateCandidateNote(value, key){
	document.getElementById('noteText2').value = value;
	document.getElementById('keyID2').value = key;
	var xhrArgs = {
            form: dojo.byId('addInlineFieldsUpdateNoteForm'),
            handleAs: "text"
        }
        //Call the asynchronous xhrPost
        var deferred = dojo.xhrPost(xhrArgs);
}

/**
 * destroys all descendents in the content area waiting to receive content
 * @param pane Content area to work in
 */
function destroyDescendants(pane){
	
	var element = dijit.byId(pane);
	desendants = element.getDescendants();
	//alert(desendants);
	if (desendants.length > 0) {
		for ( var i = desendants.length - 1; i >= 0; i--) {

			if ((dijit.byId(desendants[i]))) {
				if (temp = dijit.byId(desendants[i]).toString()) {
					if (temp = temp.split(',')[1]) {
						if (temp = temp.split('-')[1]) {
							if (temp == 'ContentPane]') { dijit.byId(desendants[i]).destroyDescendants(); }
						}
					}
				}
			}
		}
	}
}

// window pane scripts //
var bookingWindow;

function showEventBookingWindow(title, season, school) {
	bookingWindow = new dijit.Dialog({
        title: "Add events for " + title,
        style: "width: 300px",
        href: "/internal/schools/add-events-to-school/?schoolID=" + school + "&seasonID=" + season
    });
    // set the content of the dialog:
	bookingWindow.show();
}

var interviewGroupWindow;

function showInterviewGroupWindow(school, event, interview, type) {
	interviewGroupWindow = new dijit.Dialog({
        title: "Create a group interview",
        style: "width: 320px",
        href: "/internal/interview/create-group-interview/?schoolID=" + school + "&eventID=" + event + "&interviewID=" + interview + "&type=" + type
    });
    // set the content of the dialog:
	interviewGroupWindow.show();
}

var deleteInterviewSectionWindow;

function showDeleteInterviewSectionWindow(school, event, group) {
	if(dijit.byId('deleteInterviewSectionWindowID')){
		dijit.byId('deleteInterviewSectionWindowID').destroyDescendants();
		dijit.byId('deleteInterviewSectionWindowID').destroy();
	}
	deleteInterviewSectionWindow = new dijit.Dialog({
        title: "Delete an interview section",
        style: "width: 320px",
        id: "deleteInterviewSectionWindowID",
        href: "/internal/interview/delete-section/?schoolID=" + school + "&eventID=" + event + "&groupID=" + group
    });
    // set the content of the dialog:
	deleteInterviewSectionWindow.show();
}

var attachCandidateToInterviewWindow;

function showattachCandidateToInterviewWindow(school, event, interview) {
	if(dijit.byId('attachCandidateToInterviewWindowID')){
		dijit.byId('attachCandidateToInterviewWindowID').destroyDescendants();
		dijit.byId('attachCandidateToInterviewWindowID').destroy();
	}
	attachCandidateToInterviewWindow = new dijit.Dialog({
        title: "Delete an interview section",
        style: "width: 320px",
        id: "attachCandidateToInterviewWindowID",
        href: "/internal/interview/attach-candidate-to-interview/?schoolID=" + school + "&eventID=" + event + "&interviewID=" + interview
    });
    // set the content of the dialog:
	attachCandidateToInterviewWindow.show();
}

function destroyInterviewSectionDeleteWindow(){
	dijit.byId('deleteInterviewSectionWindowID').onCancel();
	dijit.byId('deleteInterviewSectionWindowID').destroyDescendants();
	dijit.byId('deleteInterviewSectionWindowID').destroy();
}

var fakeProgressWindow;

function fileUpload(form) {
	fakeProgressWindow = new dijit.Dialog({
        title: "Progress",
        content: "<div style=\"width:410px;height:50px;vertical-align:middle;text-align:center\"><div indeterminate=\"true\" dojoType=\"dijit.ProgressBar\"></div><p>Your file is being uploaded. Please wait.</p></div>"
    });
    // set the content of the dialog:
	fakeProgressWindow.show();
	dijit.byId(form).submit();
}

function contentUpload(form) {
	if(dijit.byId(form).isValid()){
	fakeProgressWindow = new dijit.Dialog({
        title: "Progress",
        content: "<div style=\"width:410px;height:50px;vertical-align:middle;text-align:center\"><div indeterminate=\"true\" dojoType=\"dijit.ProgressBar\"></div><p>Your file is being uploaded. Please wait.</p></div>"
    });
    // set the content of the dialog:
	fakeProgressWindow.show();
	dijit.byId(form).submit();
	}else{
		alert('Please complete all mandatory fields and/or attach a file')
	}
}

function filePDFMaker() {
	fakeProgressWindow = new dijit.Dialog({
        title: "Progress",
        content: "<div style=\"width:410px;height:50px;vertical-align:middle;text-align:center\"><div indeterminate=\"true\" dojoType=\"dijit.ProgressBar\"></div><p>Your pdf file is being generated. Please wait this can take up to 10 minutes. This page will refresh when complete.</p></div>"
    });
    // set the content of the dialog:
	fakeProgressWindow.show();
}

function pdfGenerationProgress(eventID) {
	fakeProgressWindow = new dijit.Dialog({
        title: "Progress",
        content: "<div style=\"width:410px;height:50px;vertical-align:middle;text-align:center\"><div indeterminate=\"true\" dojoType=\"dijit.ProgressBar\"></div><p>Your PDF's are being generated.<br/>Please wait this can take upto 10 minutes.</p></div>"
    });
    // set the content of the dialog:
	fakeProgressWindow.show();
	document.location.href = "/internal/events/produce-pdf-of-school-interview-schedule/?eventID=" + eventID;
}

function setInitialProgressBar(textField, progBar, maximumAmount){
 	 newstr =  dijit.byId(textField).attr('value');
   wordCounter = newstr.length;
      dijit.byId(progBar).update({ maximum: maximumAmount, progress:wordCounter  });
}

function updateReviewSpanClass(span, candidate){
	if(document.getElementById(span).className == "keyList review0"){
		document.getElementById(span).setAttribute("class", "keyList review1");
		updateData('internal', 'candidates', 'update-candidate-assessment', ['candidateID=' + candidate,'field=assessReviewed_can']);
	}else{
		document.getElementById(span).setAttribute("class", "keyList review0");
		updateData('internal', 'candidates', 'update-candidate-assessment', ['candidateID=' + candidate,'field=assessReviewed_can']);
	}	
}
function updateRecordSpanClass(span, candidate){
	if(document.getElementById(span).className == "keyList recordStatus0"){
		document.getElementById(span).setAttribute("class", "keyList recordStatus1");
		updateData('internal', 'candidates', 'update-candidate-assessment', ['candidateID=' + candidate,'field=assessComplete_can','value=1']);
	}else if(document.getElementById(span).className == "keyList recordStatus1"){
		document.getElementById(span).setAttribute("class", "keyList recordStatus2");
		updateData('internal', 'candidates', 'update-candidate-assessment', ['candidateID=' + candidate,'field=assessComplete_can','value=2']);
	}else{
		document.getElementById(span).setAttribute("class", "keyList recordStatus0");
		updateData('internal', 'candidates', 'update-candidate-assessment', ['candidateID=' + candidate,'field=assessComplete_can','value=0']);
	}
}

function updateAttendanceSpanClass(span, candidate, donotupdate){
	if(document.getElementById(span).className == "keyList attendance0"){
		document.getElementById(span).setAttribute("class", "keyList attendance1");
		if(donotupdate == 0){
			updateData('internal', 'candidates', 'update-candidate-assessment', ['candidateID=' + candidate,'field=assessAttendance_can','value=1','donotupdate=1']);
		}else{
			updateData('internal', 'candidates', 'update-candidate-assessment', ['candidateID=' + candidate,'field=assessAttendance_can','value=1', 'donotupdate=0']);
		}
		
	}else if(document.getElementById(span).className == "keyList attendance1"){
		document.getElementById(span).setAttribute("class", "keyList attendance2");
		updateData('internal', 'candidates', 'update-candidate-assessment', ['candidateID=' + candidate,'field=assessAttendance_can','value=2']);
	}else{
		document.getElementById(span).setAttribute("class", "keyList attendance0");
		updateData('internal', 'candidates', 'update-candidate-assessment', ['candidateID=' + candidate,'field=assessAttendance_can','value=0']);
	}
}

function updateInviteSpanClass(span){
	if(document.getElementById(span).className == "keyList invite0"){
		document.getElementById(span).setAttribute("class", "keyList invite1");
	}else{
		document.getElementById(span).setAttribute("class", "keyList invite0");
	}
}

//function to submit a mass of candidates to 

var candidateIDs = [];

function selectCandidateIDs(chosenField, candID){
 	
 	if(chosenField.checked == true){
		var s = 0;
		for(var h=0;h<candidateIDs.length;h++){ if(candidateIDs[h] == candID){ s = 1; break; } }
		if (s == 0) { candidateIDs.push(candID) }
	}else{
		for(var h=0;h<candidateIDs.length;h++){ if(candidateIDs[h] == candID){ candidateIDs.splice(h,1); break; } }
	}
}

var attachCandidateToSchoolsWindow;

function showAttachCandidateToSchoolsWindowWindow(city, season) {
	if(dijit.byId('attachCandidateToSchoolsWindowID')){
		dijit.byId('attachCandidateToSchoolsWindowID').destroyDescendants();
		dijit.byId('attachCandidateToSchoolsWindowID').destroy();
	}
	//implode the array
	idholder = candidateIDs.join(',');
	attachCandidateToSchoolsWindow = new dijit.Dialog({
        title: "Add Candidates to school lists",
        style: "width: 520px",
        id: "attachCandidateToSchoolsWindowID",
        href: "/internal/candidates/attach-candidates-to-schools/?cityID=" + city + "&seasonID=" + season + "&candidateID=" + idholder
    });
    // set the content of the dialog:
	attachCandidateToSchoolsWindow.show();
}

function submitAttachCandidatesForm(){
	var xhrArgs = {
            form: dojo.byId('attachCandidatesToSchoolForm'),
            handleAs: "text"
        }
        //Call the asynchronous xhrPost
        var deferred = dojo.xhrPost(xhrArgs);
		dijit.byId('attachCandidateToSchoolsWindowID').onCancel();

}

var attachCandidateToInterviewWindow;

function showAttachCandidateToInterviewWindow(school, event, candidate) {
	if(dijit.byId('attachCandidateToInterviewWindowID')){
		dijit.byId('attachCandidateToInterviewWindowID').destroyDescendants();
		dijit.byId('attachCandidateToInterviewWindowID').destroy();
	}
	//implode the array
	attachCandidateToInterviewWindow = new dijit.Dialog({
        title: "Add Candidate to interview",
        style: "width: 520px;height:500px",
        id: "attachCandidateToInterviewWindowID",
        href: "/internal/candidates/attach-candidate-to-interviews/?schoolID=" + school + "&eventID=" + event + "&candidateID=" + candidate
    });
    // set the content of the dialog:
	attachCandidateToInterviewWindow.show();
}

var attachGeneralWindow;

function showGeneralWindow(location, header, width) {
	if(!width){width = "520px"}
	if(dijit.byId('attachGeneralWindowID')){
		dijit.byId('attachGeneralWindowID').destroyDescendants();
		dijit.byId('attachGeneralWindowID').destroy();
	}
	//implode the array
	attachGeneralWindow = new dijit.Dialog({
        title: header,
        style: "width: " + width + ";",
        id: "attachGeneralWindowID",
        href: location
    });
    // set the content of the dialog:
	attachGeneralWindow.show();
}

function refreshGeneralWindow(){
	var location = dijit.byId('attachGeneralWindowID').href;
	var header = dijit.byId('attachGeneralWindowID').title;
	var width = dijit.byId('attachGeneralWindowID').style.replace("width:", "");
	dijit.byId('attachGeneralWindowID').onCancel();
	showGeneralWindow(location, header, width);
}

function inviteCandidateUpdate(module, controller, action, args, span, updateSpan, refresh){
	if(!args){args = []}
	//Look up the node we'll stick the text under.
    //var targetNode = dojo.byId(pane + '-ContentPane');
	
	//build the url we are getting data for
    var url = '/' + module + '/' + controller + '/' + action + '/?' + args.join('&');
    //The parameters to pass to xhrGet, the url, how to handle it, and the callbacks.
    var xhrArgs = {
        url: url, 
        handleAs: "text",
        preventCache: false,
        handle: function(error, ioargs) {
            switch (ioargs.xhr.status) {
            case 200:
            	//if(updateSpan == 1){updateInviteSpanClass(span)}
            	if(updateSpan == 1){refreshGeneralWindow()};
                break;
           default:
                alert('There was an error setting up invite, please try again.')
            }
        }
    }

    //Call the asynchronous xhrGet
    var deferred = dojo.xhrGet(xhrArgs);  
}

function addRow(tableID) {
	 
    var table = document.getElementById(tableID);

    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);

    var cell1 = row.insertCell(0);
    var fieldNumber = rowCount + 1;
    cell1.innerHTML = fieldNumber + '. <input type="text" name="newBook' + fieldNumber + '" id="newBook' + fieldNumber + '" value="" dojoType="dijit.form.TextBox" style="width:90%">';


}

function addSubjectRow(tableID) {
	 
	var selectobject = document.getElementById('filter_Subjects');
	var holder = '<option value="">Please select subject</option>';
	for (var i=0; i<selectobject.length; i++){
		holder += '<option value="' + selectobject.options[i].value + '">' + selectobject.options[i].value + '</option>';
		}
    var table = document.getElementById(tableID);

    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);

    var cell1 = row.insertCell(0);
    var fieldNumber = rowCount + 1;
    cell1.innerHTML = 'Extra Subject ' + fieldNumber + '. <select name="newSubject' + fieldNumber + '" id="newSubject' + fieldNumber + '">' + holder + '</select>';


}

function deleteRow(tableID) {
    try {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;

    for(var i=0; i<rowCount; i++) {
        var row = table.rows[i];
        var chkbox = row.cells[0].childNodes[0];
        if(null != chkbox && true == chkbox.checked) {
            table.deleteRow(i);
            rowCount--;
            i--;
        }

    }
    }catch(e) {
        alert(e);
    }
}

