/* JavaScript Document that governs the opening of PHP files, the selection of checkboxes and the highlighting of checkboxes. surveytool.js is included in most PHP scripts. 

surveytool.js incorporates functions that deals with Add, Edit, Delete, etc functions. This functions are based on the action call from the PHP script that is calling this javascript file. 


These file is included in the 6 modules that are commented seperately. The modules that uses this file are:

Main window 			-	index.php
Design window			-	design.php
Mailengine window 		-	mailengine.php
Responses window		-	responses.php
Report & Analysis win	-	report.php
PDF Engine window		-	pdfgeneration.php

Other files that incorporate this file is included in teh Surveytool documentation. Some functions are commented in this file. These commented functions are functions that have been transfered from minisurvey.js. minisurvey.js has exactly the same functions that is used here. 

Commented by: Vignash Naidu, 2007-10-29
*/


/*
Global functions and variables
-------------------------------------------------------------------------------
*/

var ie = document.all?1:0;
var ns4 = document.layers?1:0;
var antal_valda = 0;
var last_selected = null;
var last_selected_tr = null;

var selectedSurvey = "";
var authorizeString = "";

/*
This function is to be executed in the jQuery document.ready
*/
function jQueryStartContructor(){	

	/*
	$.fn.preload = function() {
		this.each(function(){
			$('<img/>')[0].src = this;
		});
	}
	
	// Usage:
	
	$(['img1.jpg','img2.jpg','img3.jpg']).preload();
	*/
	
	//Preload images
	/*
	preload_image_object = new Image();
	// set image url
	image_url = new Array();
	image_url[0] = "images/common/nav.png";
	image_url[1] = "images/common/buttons.png";
	image_url[2] = "images/common/nav-active.png";
	image_url[3] = "images/common/nav-ul-active.png";
	image_url[4] = "images/common/select-l.png";
	image_url[5] = "images/common/select-r.png";
	image_url[6] = "images/common/icon-tick.png";
	image_url[7] = "images/common/button-pop.png";
	image_url[8] = "images/common/divider.jpg";
	image_url[9] = "images/common/icon-design.jpg";
	image_url[10] = "images/common/icon-mail.jpg";
	image_url[11] = "images/common/icon-pdf.jpg";
	image_url[12] = "images/common/icon-preview.jpg";
	image_url[13] = "images/common/icon-report.jpg";
	image_url[14] = "images/common/icon-responses.jpg";
	image_url[15] = "images/common/icon-share.jpg";
	image_url[16] = "images/common/icon-survey.jpg";
	image_url[17] = "images/common/stripe-hr.jpg";
	image_url[18] = "images/common/th-bg.jpg";
	image_url[19] = "images/common/table-foot-bg.jpg";

	for(i=0; i<=image_url.length;i++){ 
		preload_image_object.src = image_url[i];
	}
*/
 
	
	/*
	Start: scripts for New Survey (Main Tab) - Kenneth Sep 2010
	*/
	
	$('#new_initial_url').keyup(function(){	
		$('#new_webaddress').html($(this).val());
	});
	
	//Show more options
	$("#newsuvey_more").toggle(function() {
		$(this).val("Less options");
		$("#surveys_new").dialog('option','height',370);
		$('#surveys_new_main').find('.new_more').show('slide');
	}, function() {
		$(this).val("More options");		
		$('#surveys_new_main').find('.new_more').hide('slide',function(){
			$("#surveys_new").dialog('option','height',300);															   
		});		
	});
	
	//check the codes entered
	$('#new_initial_url').keypress(function(e) {
		var validCode = checkCodeValid(e);
		if(!validCode){
			alert("You have entered an illegal character! \nPlease note that valid characters are alphanumerical characters in interval A-Z, a-z or 0-9.");
		}
		
		return validCode;
	});
	
	//Save create new survey
	$("#newsurvey_save").click(function(){
		
		if(!$('#new_heading').val() && !$('#new_internal_heading').val()){
			alert('Please input a survey heading.');
			return false;
		}
		
		if(!isAlphaNumeric($('#new_initial_url').val())){
			alert("You have entered illegal character(s) in your survey web address (link suffix)! \nPlease note that valid characters are alphanumerical characters in interval A-Z, a-z or 0-9.");
			$('#new_initial_url').focus();
			return false;
		}
		
		$("#surveys_new_progressbar").progressbar({value:50});
		$('.ui-progressbar-value').css('background-image','url(css/'+theme+'/images/pbar-ani.gif)');
		$('#surveys_new_loading_text').text('Creating your new survey...');	
		$('#surveys_new_main').hide();	
		$("#surveys_new_loading").show();

		$.post("surveys_save.php", $("#form_new_survey").serialize(),function(data){
			
			if(data==1){	
				$("#surveys_new_progressbar").progressbar({value:100});
				$('#surveys_new_loading_text').text('Reloading page...');	
				alert("New survey created.");
			}
			else if(data==2){	
				$("#surveys_new_progressbar").progressbar({value:100});
				$('#surveys_new_loading_text').text('Reloading page...');	
				alert("Survey copied.");
			}
			else{
				alert(data);
				//console.log(data);
			}
			
			$('#surveys_new').dialog('close');		
			
			//reload if at survey listing page
			if($('body').data('survey_listing_page')==1){
				window.location.reload();
			}
			
		});// end post
	});// end click
	
	$(".survey_tabs").mouseenter(function() {	
		$(this).addClass('active');
	}).mouseleave(function() {
		if(!$(this).hasClass('current_tab')){
			$(this).removeClass('active');
		}
	});
	
	
	$("#surveys_new").dialog({
		title: 'Create new survey',
		autoOpen: false,
		width: 750,
		height: 600,
		modal: true,
		show: 'fold',
		hide: 'fold'
	});
	
	$("#new_startdate,#new_enddate").datepicker({ 
		dateFormat: 'yy-mm-dd',
		showAnim:'fold',
		showButtonPanel: true,
		changeMonth: true,
		changeYear: true,
		onClose:function(){			
			//make sure startdate is before stopdate
			if($('#new_startdate').val() > $('#new_enddate').val()){
				alert("This is an invalid selection.\nThe start date is after the stop date.");
				$('#new_startdate').val($('#new_enddate').val()); 
			}			
		}
	});
	
	/*
	End: scripts for New Survey (Main Tab) - Kenneth Sep 2010
	*/
	
	//Delete survey
	$("#delete_survey").click(function(){
		
		var surveys_delete = $("#surveys_delete");
		var form_serialize = $("#form_delete_survey").serialize();
		//alert($(surveys_delete).find(".micp"));
		$(surveys_delete).find(".progressbar").progressbar({value:50});
		$(surveys_delete).find('.ui-progressbar-value').css('background-image','url(css/'+theme+'/images/pbar-ani.gif)');
		$(surveys_delete).find('.loading_text').text('Deleting survey data...');	
		$(surveys_delete).find('.main').hide();	
		$(surveys_delete).find(".loading").show();
		
		//alert(form_serialize);
		
		$.post("surveys_save.php",form_serialize,function(data){
			
			if(data==1){	
				$("#surveys_delete").find(".progressbar").progressbar({value:100});
				$('#surveys_delete').find(".loading_text").text('Reloading page...');	
				alert("Survey deleted.");
			}
			else{
				alert(data);				
			}	
			
			//window.location.href='/surveytool/?m=2';
            window.location.reload ();
		});// end post
	});// end click
	
	/*
	Changes made to the page
	Prompt if there're changes and in Edit mode
	*/
	//alert($('body').data('promptChanges')?"1":"2");
	if($('body').data('promptChanges')){
		//Sorting moved
		$('.dragHandle,.delete_qns').click(function(){	
			$('body').data('changes',true);
		});
		
		$('textarea,select').change(function(){
			if($(this).attr('id')!='mall_subsection'){
				$('body').data('changes',true);
			}
		});
	
		window.onbeforeunload = function() { 
			if($('body').data('changes')){
				return "You have unsaved changes.";
			}
		};
	}
	
	//Convert to HTML entities when doing search
	$('form#form_search').submit(function(){
		$(this).find('#Search').val(convertToNumCharRef($(this).find('#Search').val()));
		$(this).find('#Search').attr('readonly','readonly');
	});
	
	$("#surveys_delete").dialog({		
		autoOpen: false,
		width: 700,
		modal: true,
		show: 'fold',
		hide: 'fold'
	});
	
	//Waiting window
	$("#main_waiting").dialog({
		autoOpen: false,
		closeOnEscape: false,
		width: 200,
		modal: true,
		open: function(){
			$('.ui-dialog-titlebar-close').hide();
		}
	});
	
	//Blank dialog box for general use
	$("#blank_dialog").dialog({		
		autoOpen: false,		
		modal: true,
		show: 'fold',
		hide: 'fold'
	});
}

function jQueryEndContructor(){
	$('#page_loading').hide();
	$('#Container').show();
	$('#page_main').show();
}


function InitializeDialog (progressBarValue, loadingText, title, height, width)
{
	var blank_dialog = $("#blank_dialog");
	$(blank_dialog).find(".progressbar").progressbar({value:progressBarValue});
	$(blank_dialog).find('.ui-progressbar-value').css('background-image','url(css/'+theme+'/images/pbar-ani.gif)');
	$(blank_dialog).find('.loading_text').text(loadingText);	
	$(blank_dialog).find('.main').hide();	
	$(blank_dialog).find(".loading").show();
	
	$(blank_dialog).dialog("option","title",title);		
	if (height != null && height != ''){
		$(blank_dialog).dialog("option","height",($(window).height()>height)?height:$(window).height()-50);	
	}
	else{
		$(blank_dialog).dialog("option","height",($(window).height()>600)?'auto':$(window).height()-50);	
	}
	
	if (width != null && width != ''){
		$(blank_dialog).dialog("option","width",($(window).width()>width)?width:$(window).width()-50);				
	}
	else{
		$(blank_dialog).dialog("option","width",($(window).width()>800)?'auto':$(window).width()-50);				
	}
	
	$(blank_dialog).dialog("open");
	
	return blank_dialog;
}
function FinalizeDialog ()
{
	var blank_dialog = $("#blank_dialog");
	$(blank_dialog).find(".progressbar").progressbar({value:100});			
	$(blank_dialog).find(".loading").hide();
	$(blank_dialog).find('.main').show();
}

/*
This maximise the div in the Design section. Such that the scroll bars is within the div instead of the body. This allows the user to always access the menu & save button
*/
function maximiseDesignPage(){
	
	//Problems with this for IE 7, thus don't maximise for IE7 & below
	if($.browser.msie && $.browser.version<8){
		return false;
	}
	
	doSizing();
	
	$(window).resize(function(){
        doSizing();
    });
	
	function doSizing(){
		$('html').css('overflow-y','hidden');
		$('#sortable').height($(window).height()-340);
	}
}

//This is the click function for all the questions in Design

function deleteQuestion(question_type){
	$('body').data('delete_questions',0);
	$(".delete_qns").click(function(){		
		//check if the question can be deleted (that it's not being used as surveyflow condition)
		
		var deleteQuestion = $(this);
		$.ajax({
			url:"design_preferences_save.php",
			type:"POST",
			data:{'i_micpnumber':micpnumber,'eKey':eKey,'save_type':'checkRouting','question_type':question_type+deleteQuestion.attr('id')},
			success:function(data){				
				if(data==false){					
					deleteQuestion.closest('.div-sortable').hide('highlight',function(){																   
						$(this).remove();
						$('body').data().delete_questions++;
					});			
				}
				else{
					//console.log(data+typeof(data));
					alert('Question could not be deleted as it is being used by the following question(s) as a condition:\n'+data.join(",")+'.\n\nPlease remove these condtion(s) from Surveyflow and try again.');
				}
			},
			error:function(jqXHR, textStatus, errorThrown){
				alert("There is an error. Please contact support.");
				console.log(jqXHR);
				console.log(textStatus);
				console.log(errorThrown);
			},
			dataType:'json'			
		}); //end ajax
		
	});//end click
}

function getSurveyAccess(level){
	
	if(!authorizeString)
		return true;
	
	if(level == 'design'){
		return (authorizeString.substr(0,1) == 'T'||authorizeString=='HIGH');
	}
	else if(level == 'responses'){
		return (authorizeString.substr(1,1) == 'T'||authorizeString=='MEDIUM');
	} else if(level == 'report'){
		return (authorizeString.substr(2,1) == 'T'||authorizeString=='LOW');
	}
	else
		return false
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_preloadImages() { //v3.0
  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];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

/*
Shifted here (Kenneth Lim 28 July 2010)
Input code checker
Used in Coding Section, Frontpage
*/
function checkCodeValid(e){
	
	//firefox has to use the event passed in as a parameter
	//ie uses the event as a global variable
	evt = (e) ? e : event;
	var charCode = (evt.which) ? evt.which : evt.keyCode;
	
	if ( charCode ==  13 ) {
		return false;
	}
	
	//48-57 = numeric, 65-90 = alphabets, 97-122 = , 8 = backspace, 9 = tab, 37-40 = arrow keus, 46 = delete, special latin chars = 192-255
	//underscore = 95, parenthesis = 40,41, minus = 45
	if ((charCode >= 48 && charCode <= 57) || (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122) || charCode == 8 || charCode == 9 || (charCode >= 37 && charCode <= 40) || charCode == 46 || (charCode >= 192 && charCode <= 255) || charCode == 95 || charCode == 40 || charCode == 41 || charCode == 45) {
		//alert(charCode);
		return true;
	}
	//alert(charCode);
	return false;
	
}

function isAlphaNumeric(str){

	if(str.match(/[^(a-z|0-9)]/i)){
		return false;
	}
	return true;
}

/*
This convert characters non-engligh characters to Number Character References (eg &#1234). Simulates HTML form POST.
*/
function convertToNumCharRef(s){
  ret = '';
  for (i=0; i<s.length; i++) {
    charCode = s.charCodeAt(i);
	
	//Keep normal characters as it is
    if ((charCode <= 127))
      ret += s.charAt(i);
    else
      ret += '&#' + charCode + ';';
  }
  return ret;
}

/* 
Function that takes cares of highlighting the checkbox row and pulling up the checkbox (row id). Row id may differ from file to file.
*/

function setBackground(chkbox){
	var chkbox_org = chkbox;
	if (ie) {
		while (chkbox.tagName!="TR"){
			chkbox=chkbox.parentElement;
		}
	} else {
		while (chkbox.tagName!="TR") {
			chkbox=chkbox.parentNode;
		}
	}
	
	if (chkbox_org.checked) {
		if (last_selected != null) {
			last_selected.checked = false;		
			$(last_selected_tr).removeClass("selected");
			antal_valda--;
		}
		chkbox_org.checked = true;
		last_selected = chkbox_org;
		last_selected_tr = chkbox;
		$(chkbox).addClass("selected");
		antal_valda++;
	
	}
	else {
		$(chkbox).removeClass("selected");
		last_selected = null;
		antal_valda--;
		
	}
}

/*
Checkbox selection validator

single: Single or multiple checkboxes allowed
parent: id of parent container that contains the checkboxes
itemtype: name to display to users when prompting

returns true if ok, else prompt alert and return false.
*/
function checkSelection(single,parent,itemType){

    //Start - Rashid - if user is accessing something that is not allowed on that page e.g., edit contact on design email page
    if (typeof $('#'+parent)[0] == "undefined")
    {
        alert ("Please goto "+itemType+" list first and select this option");
        return false;
    }
    //End - Rashid - if user is accessing something that is not allowed on that page e.g., edit contact on design email page

	itemType = (itemType)?itemType:"item";
	var count = $('#'+parent).find('input:checked').length;
	var txtNoItems = "Please select "+((single)?"":"at least ")+"1 "+itemType+" from the list";
	var txtOnlyItem = "Please select only 1 "+itemType+" from the list";
	if(count==0){
		alert(txtNoItems);
		return false;
	}
	else if(single && count>1){
		alert(txtOnlyItem);
		return false;
	}
	
	return true;
}

/*
Table row highligher (multiple selections)

parent: class of parent row
thisitem: this selected item
selectClass: class to add to the row
checkclass: class of all the checkboxes
chkall: id of check all box
chkalltotal: id of check all (including those not shown on this page)
*/
function rowSelector(parent,thisitem,selectClass,checkclass,chkall,chkalltotal){

    
	//Check all 
	if($(thisitem).attr('id')==chkall || $(thisitem).attr('id')==chkalltotal)
    {
		if($(thisitem).attr('checked')){
			$('.'+parent).addClass(selectClass);
			if($(thisitem).attr('id')==chkalltotal){
				//Check everything else
				$('input.'+checkclass).attr('checked',true);
			}
			else if($(thisitem).attr('id')==chkall){
				//Check everything except the Checl All Total
				$('input.'+checkclass).not('#'+chkalltotal).attr('checked',true);
			}
		}
		else{
			$('.'+parent).removeClass(selectClass);
			$('input.'+checkclass).attr('checked',false);
		}
	}
	//Normal checkbox
	else{
	
		if($(thisitem).attr('checked')){
			$(thisitem).closest('.'+parent).addClass(selectClass);
		}
		else{
			$(thisitem).closest('.'+parent).removeClass(selectClass);
		}
		if(chkall){
			//remove the checkall box
			$('#'+chkall).attr('checked',false);
		}
		if(chkalltotal){
			//remove the checkall box
			$('#'+chkalltotal).attr('checked',false);
		}
	}	
}

// F�nsterfunktioner --- M�ste saneras :)

function NewWindowURL(url,windowname,w,h,scroll){
LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
TopPosition = (screen.availheight) ? (screen.availheight-h)/2 : 0;
settings =
'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable=yes,toolbar=yes,location=yes';
	try { // try closing old window if opened
		if (NewWin != null) {
			NewWin.close();
		}
	} catch (err) {}
	NewWin = window.open(url,windowname,settings)
	NewWin.focus();
}

function NewWindow(url,windowname,w,h,scroll){
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	//resizable has to be set 1st to allow resizable.
	//For conditional setting when it gets long horizontally.
	settings = 'resizable=1,height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll;
	try { // try closing old window if opened
		if (win != null) {
			win.close();
		}
	} catch (err) {}
	win = window.open(url,windowname,settings)
	win.focus();
	}

function NewWindow2(url,windowname,w,h,scroll){
LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
TopPosition = (screen.availheight) ? (screen.availheight-h)/2 : 0;
settings =
'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable,toolbar,location=yes';
	try { // try closing old window if opened
		if (win2 != null) {
			win2.close();
		}
	} catch (err) {}
	win2 = window.open(url,windowname,settings)
	win2.focus();
}

function NewWindow3(url,windowname,w,h,scroll){
LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
TopPosition = (screen.availheight) ? (screen.availheight-h)/2 : 0;
settings =
'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable';
	try { // try closing old window if opened
		if (win3 != null) {
			win3.close();
		}
	} catch (err) {}
	win3 = window.open(url,windowname,settings)
	win3.focus();
}

function NewWindowMax(url,windowname,w,h,scroll){
LeftPosition = 0;
TopPosition = 0;
settings =
'height='+screen.availHeight+',width='+screen.availWidth+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable';
	try { // try closing old window if opened
		if (winMax != null) {
			winMax.close();
		}
	} catch (err) {}
	winMax = window.open(url,windowname,settings)
	winMax.focus();
}

function change_selected(oObject) {

  document.all[current_select].className='s';
  current_select = oObject.id;
  oObject.className='sw';
}

//Individual Preview for the different sections
function pmp_individual_preview(are,eKey,area) {
	NewWindow2('/preview.php?are='+are+'&eKey='+eKey+'&area='+area,'minisurvey_preview',800,600,'YES');
}

/* From minisurvey.js. This is pasted here for comparison sake - Vignash Naidu 31/10/07
function change_selected(oObject) {

  document.all[current_select].className='s';
  current_select = oObject.id;
  oObject.className='sw';
}
*/

/*

-------------------------------------------------------------------------------
*/



/*
Shared javascript functions used for pop-up window Analysis Group accessed from Responses window & Report & Analysis window 
The preceding 2 functions are used in Analysis Group as well.
-------------------------------------------------------------------------------
*/
//alert("continue saving new survey");
function pmp_select(are,eKey,selected){
	
	if(!are || !eKey){
		alert("You've reached an invalid page");
		return false;
	}
	
	$('body').data('are',are);
	$('body').data('eKey',eKey);
	$('body').data('selected',selected);
	
	var blank_dialog = $("#blank_dialog");
	
	$(blank_dialog).find(".progressbar").progressbar({value:50});
	$(blank_dialog).find('.ui-progressbar-value').css('background-image','url(css/'+theme+'/images/pbar-ani.gif)');
	$(blank_dialog).find('.loading_text').text('Loading analysis groups...');	
	$(blank_dialog).find('.main').hide();	
	$(blank_dialog).find(".loading").show();
	
	$(blank_dialog).dialog("option","title",'Analysis Groups');		
	$(blank_dialog).dialog("option","height",620);				
	$(blank_dialog).dialog("option","width",700);
	$(blank_dialog).dialog("open");		
	
	$(blank_dialog).find(".main").load('main_analysisgroups.php',{'are':are,'eKey':eKey,'selected':selected},function(){
		
		var blank_dialog = $("#blank_dialog");
		
		$(blank_dialog).find(".progressbar").progressbar({value:100});			
		$(blank_dialog).find(".loading").hide();
		$(blank_dialog).find('.main').show();
		
		$(blank_dialog).find("#i_date_from,#i_date_to").datepicker({ 
			dateFormat: 'yy-mm-dd',
			showAnim:'fold',
			showButtonPanel: true,		
			changeMonth: true,
			changeYear: true,
			onClose:function(){
				//make sure startdate is before stopdate
				if($('#i_date_from').val() && $('#i_date_to').val() && $('#i_date_from').val() > $('#i_date_to').val()){
					alert("This is an invalid selection.\nThe from date is after the to date.");
					$('#i_date_from').val($('#i_date_to').val()); 
				}
			}
		});
		
		//New analysis
		$(blank_dialog).find("#analysis_new").click(function(){				
			pmp_select($('body').data('are'),$('body').data('eKey'),0);
		});		
		//end click
		
		//Save analysis
		$(blank_dialog).find("#analysis_save").click(function(){				
			
			$(blank_dialog).find(".sbttn").attr('disabled','disabled');
			
			$(blank_dialog).find(".action").val('analysis_groups_save');

            jQuery('#form_analysis_groups').find('INPUT[type="text"],INPUT[type="checkbox"]').each(function(){
                $(this).val(convertToNumCharRef($(this).val()));
            });
			
			$.post("main_save.php",$(blank_dialog).find("#form_analysis_groups").serialize(),function(data){
																								
				if(data==1){
					alert("Analysis group saved.");
                    //Reload the analysis group to update data
					pmp_select(are,eKey,selected);
				}
				else{
					alert(data);
					$(blank_dialog).find(".sbttn").attr('disabled','');
				}				
				//pmp_select($('body').data('are'),$('body').data('eKey'),$('body').data('selected'));
				
			});//end .post		
		});		
		//end click		
		
		//Copy analysis
		$(blank_dialog).find("#analysis_copy").click(function(){				
			
			$(blank_dialog).find(".sbttn").attr('disabled','disabled');
			
			$(blank_dialog).find(".action").val('analysis_groups_copy');
			
			$.post("main_save.php",$(blank_dialog).find("#form_analysis_groups").serialize(),function(data){
				
				var result = data.split(":");
				if(result[0]==1){
					alert("Analysis group copied.");
					//alert(are+":"+eKey+":"+selected)
                    //Reload the analysis group to the copied one
					pmp_select(are,eKey,result[1]);
				}
				else{
					alert(data);
				}
				
			});//end .post		
		});		
		//end click		
		
		//Delete analysis
		$(blank_dialog).find("#analysis_delete").click(function(){				
			
			$(blank_dialog).find(".sbttn").attr('disabled','disabled');
			
			$(blank_dialog).find(".action").val('analysis_groups_delete');
			
			$.post("main_save.php",$(blank_dialog).find("#form_analysis_groups").serialize(),function(data){
																								
				if(data==1){
					alert("Analysis group deleted.");
					pmp_select(are,eKey,0);
				}
				else{
					alert(data);
				}
				
			});//end .post		
		});		
		//end click

        //Delete all analysis groups
		$(blank_dialog).find("#analysis_delete_all").click(function(){

            confirm_flag = confirm ("Are you sure you want to delete all analysis groups?");
            if (confirm_flag)
            {
                $(blank_dialog).find(".sbttn").attr('disabled','disabled');

                $(blank_dialog).find(".action").val('analysis_groups_delete_all');

                $.post("main_save.php",$(blank_dialog).find("#form_analysis_groups").serialize(),function(data){

                    if(data==1){
                        alert("Analysis group deleted.");
                        pmp_select(are,eKey,0);
                    }
                    else{
                        alert(data);
                    }

                });//end .post
            }
		});
		//end click
		
		//Delete multiple analysis
		$(blank_dialog).find("#analysis_delete_multiple").click(function deletemultiple(){				
			
			$(blank_dialog).find(".sbttn").attr('disabled','disabled');
					
			$(blank_dialog).find(".main").load('main_analysisgroups_deletegroups.php',{'are':$('body').data('are'),'eKey':$('body').data('eKey')},function(){
				
				
								
				$(blank_dialog).find("#analysis_delete_multiple_button").click(function(){
					
					var count_id = $('.deletegroups_id:selected').length;
					
					if(count_id==0){
						alert('Please select at least 1 analysis group.');
						return false;
					}
					
					if(confirm('Delete '+count_id+' analysis group(s)?')){
						$.post("main_save.php",$(blank_dialog).find("#form_analysisgroup_deletegroups").serialize(),function(data){
							
							if(data==1){
								alert("Analysis group(s) deleted.");
							}
							else{
								alert(data);
							}
							
							deletemultiple()
							
						});//end .post	
					}
				});
				
				$(blank_dialog).find("#analysisgroup_cancel").click(function(){
					pmp_select($('body').data('are'),$('body').data('eKey'),0);
				});
			});					
		});		
		//end click		
		
		//Autogenerate analysis
		$(blank_dialog).find("#analysis_autogenerate").click(function(){				
			
			$(blank_dialog).find(".sbttn").attr('disabled','disabled');
			
			pmp_analysisgroups_autogenerate();				

		});		
		//end click		
		
		//Change analysis
		$(blank_dialog).find("#analysis_selection").change(function(){							
			$(blank_dialog).find(".sbttn").attr('disabled','disabled');							
			pmp_select($('body').data('are'),$('body').data('eKey'),$(this).val());				

		});
		//end change
		
		//clear dates
		$(blank_dialog).find("#clear_dates").click(function(){							
			$(blank_dialog).find("#i_date_from,#i_date_to").val('');
		});
		//end clear
		
		//Reload page on close
		$(blank_dialog).dialog({
		   close: function(){
			   window.location.reload();
			  }
		});
		
	});
	//end load
	/*
	NewWindow('select_criteria.php?eKey='+eKey+'&are='+are,'minisurvey_selection',580,500,'YES');
	*/
}

function pmp_analysisgroups_autogenerate(){
	
	if(!$('body').data('are') || !$('body').data('eKey')){
		alert("You've reached an invalid page");
		return false;
	}
	
	var blank_dialog = $("#blank_dialog");
	
	$(blank_dialog).find(".progressbar").progressbar({value:50});
	$(blank_dialog).find('.ui-progressbar-value').css('background-image','url(css/'+theme+'/images/pbar-ani.gif)');
	$(blank_dialog).find('.loading_text').text('Loading analysis groups...');	
	$(blank_dialog).find('.main').hide();	
	$(blank_dialog).find(".loading").show();
	
	$(blank_dialog).dialog("option","title",'Analysis Groups - Auto generate');		
	$(blank_dialog).dialog("option","height",620);				
	$(blank_dialog).dialog("option","width",600);				
	$(blank_dialog).dialog("open");		
	
	$(blank_dialog).find(".main").load('main_analysisgroups_autogenerate.php',{'are':$('body').data('are'),'eKey':$('body').data('eKey'),'selected':$('body').data('selected')},function(){
		
		var blank_dialog = $("#blank_dialog");
		
		$(blank_dialog).find(".progressbar").progressbar({value:100});			
		$(blank_dialog).find(".loading").hide();
		$(blank_dialog).find('.main').show();
		
		$(blank_dialog).find("#i_date_from,#i_date_to").datepicker({ 
			dateFormat: 'yy-mm-dd',
			showAnim:'fold',
			showButtonPanel: true,			
			changeMonth: true,
			changeYear: true,
			onClose:function(){
				//make sure startdate is before stopdate
				if($('#i_date_from').val() && $('#i_date_to').val() && $('#i_date_from').val() > $('#i_date_to').val()){
					alert("This is an invalid selection.\nThe from date is after the to date.");
					$('#i_date_from').val($('#i_date_to').val()); 
				}
			}
		});

		//Autogenerate analysis
		$(blank_dialog).find("#autogenerate_criteria").click(function(){				
			
			$(blank_dialog).find(".sbttn").attr('disabled','disabled');
			$(blank_dialog).find("#name_prefix").val(  convertToNumCharRef($(blank_dialog).find("#name_prefix").val())       );
			$.post("main_save.php",$(blank_dialog).find("#form_analysisgroup_autogenerate").serialize(),function(data){
				
				if(data==1){
					alert("Analysis groups generated.\n\nNote: Groups with the same name are not generated.");
				}
				else{
					alert(data);
				}
				
				pmp_select($('body').data('are'),$('body').data('eKey'),0);
				
			});//end .post		
		});		
		//end click			
		
		//Cancel
		$(blank_dialog).find("#autogenerate_cancel").click(function(){				
			
			$(blank_dialog).find(".sbttn").attr('disabled','disabled');
				
			pmp_select($('body').data('are'),$('body').data('eKey'),0);				
			
		});		
		//end click			
	});
}


function pmp_copy() {
	NewWindow('newsurvey_create.php?are='+selectedSurvey+'&eKey='+encryptedKey,'surveytool','710','470','NO');
}

function pmp_create(copyFlag) {
	//NewWindow('newsurvey_create.php','surveytool','710','470','NO');
	var surveys_new_main = $('#surveys_new_main');
	//Hide extra options
	$(surveys_new_main).find('.new_more').hide();
	$(surveys_new_main).find('#newsuvey_more').hide();
	$(surveys_new_main).find('.copy_question_text').hide();
	
	//Set Loading GUI
	$(surveys_new_main).hide();	
	$("#surveys_new_loading").show();
	$("#surveys_new_progressbar").progressbar({value:20});
	$('.ui-progressbar-value').css('background-image','url(css/'+theme+'/images/pbar-ani.gif)');
	$('#surveys_new_loading_text').text('Loading userlist...');	
	
	if(copyFlag){
		$('#surveys_new').dialog('option','title','Copy survey');
		$(surveys_new_main).find('.action').val('copy_survey');
		$(surveys_new_main).find('.i_micpnumber').val(selectedSurvey);
		$(surveys_new_main).find('.eKey').val(encryptedKey);
		$(surveys_new_main).find('.newsurvey').val('');	
	}
	else{
		$('#surveys_new').dialog('option','title','Create new survey');	
		$(surveys_new_main).find('.action').val('create_new_survey');
		$(surveys_new_main).find('.newsurvey').val('1');			
	}
	
	//Open create new surveys
	$('#surveys_new').dialog({ height: ($(window).height()>650)?650:$(window).height()-50 });
	$('#surveys_new').dialog('open');		
	
	//Allow the dialog to open before loading
	setTimeout("loadNewsurveyUsers("+copyFlag+")",500);	
	$("#surveys_new_progressbar").progressbar({value:40});
}

function loadNewsurveyUsers(copyFlag){

	//populate user listing if not populated yet
	if(!$('body').data('newsurveyUserList')){		
		$.ajax({
		  type: 'POST',
		  url: 'surveys_save.php',
		  data: {'newsurvey':1,'action':'get_newsurvey_userlist'},
		  async: false,
		  dataType: 'json',
		  error: function(jqXHR, textStatus, errorThrown){
			  alert("There are some problems. Please contact us for assistance if problem persists.\n\n"+jqXHR+":"+textStatus+":"+errorThrown);
		  },
		  success: function(data){					  
			
			$("#surveys_new_progressbar").progressbar({value:60});	
			
			if($(data).length>0){
				$('body').data('newsurveyUserList',true);

				//Populate user list
				$.each(data, function(index, val) {
					
					var new_row = "<option></option>";					
					//add the new row
					$('#new_main_user').append($(new_row).val(val['id']).html(val['lastname']+","+val['firstname']+" ("+val['company']+")"));
				});
				
				
			}			
			$("#surveys_new_progressbar").progressbar({value:80});	
		  }		  
		});//end post
	}//end if
	else{
		//clear old data 
		$('#form_new_survey')[0].reset();	
	}

	//copied survey
	if(copyFlag){
		
		$('#surveys_new_loading_text').text('Loading copied survey...');	
	
		$.ajax({
		  type: 'POST',
		  url: 'surveys_save.php',
		  data: {'i_micpnumber':selectedSurvey,'eKey':encryptedKey,'action':'get_copy_survey_info'},
		  async: false,
		  dataType: 'json',
		  success: function(data){
			 //data = decodeURIComponent( escape( data ) );
			//alert(data);
			//console.log(data);
			var surveys_new_main = $('#surveys_new_main');
			
			$("#surveys_new_progressbar").progressbar({value:90});	

			if(!data['ajaxError']){
				//alert("1");
				//Populate copy form
				$.each(data, function(index, val) {
					$(surveys_new_main).find('#'+index).val(val);
					//console.log(val);
				});											
				
				//Set copied settings
				$(surveys_new_main).find('.action').val('create_copied_survey');
				$(surveys_new_main).find('#new_heading').val($(surveys_new_main).find('#new_heading').val()+' (copy of '+selectedSurvey+')')
				$(surveys_new_main).find('.copy_question_text').show();
				$(surveys_new_main).find('.copy_questions').attr('disabled','disabled');
			}
			else{
				//alert("2");
				$(surveys_new_main).find('#newsurvey_save').attr('disabled','disabled');
				alert(data['ajaxError']);
			}
		  }		  
		});//end post		
	}
	
	//select main user
	$('#new_main_user').val(newsurvey_mainuser);
	
	
	$("#surveys_new_progressbar").progressbar({value:100});	
	
	$('#surveys_new_progressbar').progressbar('destroy');
	$('#surveys_new_main').show();
	$('#surveys_new_loading').hide();					
}


/*
-------------------------------------------------------------------------------
*/



/*	
Function for opening Report and Analysis window
-------------------------------------------------------------------------------
*/
function pmp_report() {
  if (getSurveyAccess('report'))
  	{
  		//NewWindowMax('report.php?are='+selectedSurvey+'&eKey='+encryptedKey,'minisurvey_report',1000,650,'NO');
        window.location = 'report.php?are='+selectedSurvey+'&eKey='+encryptedKey;
	}
  else
  	{
		alert("You are not authorized to do this action for the selected survey.");
	}
}
/*
-------------------------------------------------------------------------------
*/

/*
Function for opening Report Distribution window
-------------------------------------------------------------------------------
*/
function pmp_reportdistribution() {
    window.location = 'report_distribution.php?are='+selectedSurvey+'&eKey='+encryptedKey;
}
/*
-------------------------------------------------------------------------------
*/


/*
Function for opening Report Distribution window
-------------------------------------------------------------------------------
*/
function pmp_surveys() {
    window.location = 'index.php?m=2';
}
/*
-------------------------------------------------------------------------------
*/




/*
Function for opening Responses window
-------------------------------------------------------------------------------
*/
function pmp_responses() {
  if (getSurveyAccess('responses'))
  	{
  	    window.location = 'responses.php?are='+selectedSurvey+'&eKey='+encryptedKey;
	}
  else
  	{
		alert("You are not authorized to do this action for the selected survey.");
	}
}
/*
-------------------------------------------------------------------------------
*/



/*
Function for opening Mailengine window
-------------------------------------------------------------------------------
*/
function pmp_mail() {
  //NewWindowMax('mailengine.php?are='+selectedSurvey+'&eKey='+encryptedKey,'minisurvey_mail',1000,650,'YES');
  window.location = 'mailengine.php?are='+selectedSurvey+'&eKey='+encryptedKey;
}
/*
-------------------------------------------------------------------------------
*/




/*
Function for opening Design window
-------------------------------------------------------------------------------
*/
function pmp_design() {
	if(getSurveyAccess('design')){
		window.location = 'design.php?are='+ selectedSurvey+'&eKey='+encryptedKey;
		
	}
	else{
		alert("You are not authorized to do this action for the selected survey.");
	}
}
/*
-------------------------------------------------------------------------------
*/








/*
Main window / Share Survey tab 
-------------------------------------------------------------------------------
*/
function pmp_share() {
	if(getSurveyAccess('design')){
		
		var dialog = InitializeDialog(50, "Loading share survey...", "Share survey", 400, 750);
		
		dialog.find('#main_content').load('surveys_share.php',{'are':selectedSurvey,'eKey':encryptedKey},function(){
			/*
			Start: scripts for Share Survey (Main Tab) - Kenneth Sep 2010
			*/
			
			//Share Survey: Add
			$("#add_access").click(function(){
																  
				$(".sbttn").attr('disabled','disabled');
				
				$.post("surveys_save.php", $("#form_share_survey").serialize(),function(data){
																						   
					var result = data.split(':');
					
					if(result[0]==1){
						pmp_share();
					}
					else{
						alert(data);
					}
					
					$(".sbttn").attr('disabled','');
					
				});//end .post		
			});// end click
			
			//Share Survey: Delete
			$(".delete_sharedsurvey").click(function(){
																  
				$(".sbttn").attr('disabled','disabled');		
				$('body').data('del_access',$(this).attr('id'));
				var micp = $('#form_share_survey').find('.micp').val();
				$.post("surveys_save.php",{'i_micpnumber':micp,'eKey':$('#form_share_survey').find('.eKey').val(),'action':'delete_user_access','accessid':$(this).attr('id')},function(data){
																									
					if(data==1){
						$('#'+$('body').data('del_access')).parent().parent().remove();
					}
					else{
						alert(data);
					}
					
					$(".sbttn").attr('disabled','');
					
				});//end .post		
			});// end click
			
			
			/*
			End: scripts for Share Survey (Main Tab) - Kenneth Sep 2010
			*/
		});
		
		FinalizeDialog();
		
	}
	else{
		alert("You are not authorized to do this action for the selected survey.");
	}
	
  //NewWindow3('share_survey.php?are='+selectedSurvey+'&eKey='+encryptedKey,'minisurvey_share',670,350,'NO');
}

/*
Main window / Preview tab 
-------------------------------------------------------------------------------
*/

function pmp_preview(micp){
	var surveyid = (micp)?micp:selectedSurvey;
  NewWindow2('/unset_cookie35.php?are='+surveyid,'minisurvey_preview',900,600,'YES');
}

function pmp_golive(micpnr) {
  NewWindow3('survey_golive.php?are='+micpnr,'minisurvey_dialog',400,180,'NO');
}

function pmp_delete(surveytitle) {
	
	if (getSurveyAccess('design')){
		//NewWindow3('survey_delete.php?are='+selectedSurvey+'&eKey='+encryptedKey,'mainwindow_delete',710,220,'NO');
		
		var surveys_delete = $('#surveys_delete');
		
		surveytitle = (surveytitle)?surveytitle:all_surveys[selectedSurvey]['title'];
		//alert(selectedSurvey+":"+encryptedKey);
		//Set the settings
		$(surveys_delete).find('.action').val('delete_survey');
		$(surveys_delete).find('.i_micpnumber').val(selectedSurvey);
		$(surveys_delete).find('.eKey').val(encryptedKey);
		$(surveys_delete).find('.newsurvey').val('');			
		$(surveys_delete).find('.delete_survey_name').text(surveytitle);			
		$(surveys_delete).dialog("option","title","Delete survey ["+surveytitle+"]");		
	
		$(surveys_delete).find('.loading').hide();
		$(surveys_delete).find('.main').show();

		//Open delete surveys
		$(surveys_delete).dialog("open");
		
	}
  else
  	{
		alert("You are not authorized to do this action for the selected survey.");
	}
  
}
/*
-------------------------------------------------------------------------------
*/



/*
Main window /  User tab 
-------------------------------------------------------------------------------
*/

function PMP_user_edit() {
	//NewWindow('user_edit.php?id='+selectedSurvey+'&eKey='+encryptedKey,'surveytool','720','420','YES');
	//call the function from user.js
	USER_user_edit(selectedSurvey);
}

function PMP_user_delete() {
	//NewWindow('user_delete.php?id='+selectedSurvey+'&eKey='+encryptedKey,'surveytool','720','320','NO');
	//call the function from user.js
	USER_user_delete(selectedSurvey);
}

function PMP_user_new() {
	//call the function from user.js
	USER_user_edit();
}

function PMP_user_view() {
	//NewWindow('user_sharedsurveys.php?id='+selectedSurvey+'&eKey='+encryptedKey,'surveytool','670','350','YES');
	//call the function from user.js
	USER_user_sharedsurveys(selectedSurvey);
}

/*
-------------------------------------------------------------------------------
*/




/*
Main window / Account tab 
-------------------------------------------------------------------------------
*/

function PMP_account_edit() {
	//NewWindow('account_edit.php?acc_id='+selectedSurvey+'&eKey='+encryptedKey,'surveytool','650','460','NO');
	//call the function from user.js
	ACCOUNT_account_edit(selectedSurvey);
}

function PMP_account_delete() {
	//NewWindow('account_edit.php?del_acc_id='+selectedSurvey+'&eKey='+encryptedKey,'surveytool','500','280','NO');
	//call the function from user.js
	ACCOUNT_account_delete(selectedSurvey);
}

function PMP_account_new() {
	//NewWindow('account_edit.php','surveytool','650','460','NO');
	//call the function from user.js
	ACCOUNT_account_new();
}
/*
-------------------------------------------------------------------------------
*/




/*
Kenneth Lim
04 April 08
KB Supplier window
-------------------------------------------------------------------------------
*/
function kb_supplier_delete() {
	NewWindow('','kb_supplier_popup',450,350,'YES');
	form2.exportera.value = 'delete';
	form2.submit();
}

function kb_supplier_add() {
	NewWindow('','kb_supplier_popup',700,250,'YES');
	form2.exportera.value = 'add';
	form2.submit();
}

function kb_supplier_edit() {
	NewWindow('','kb_supplier_popup',700,400,'YES');
	form2.exportera.value = 'edit';
	form2.submit();
}

function kb_supplier_multi() {
	NewWindow('','kb_supplier_popup',700,400,'YES');
	form2.exportera.value = 'multi';
	form2.submit();
}

function kb_supplier_open() {
	NewWindow('','kb_supplier_popup',700,400,'YES');
	form2.exportera.value = 'open';
	form2.submit();
}

function kb_supplier_logo() {
	NewWindow('','kb_supplier_popup',700,400,'YES');
	form2.exportera.value = 'logo';
	form2.submit();
}

/*
-------------------------------------------------------------------------------
*/

/*
Kenneth Lim
04 April 08
KB Category window
-------------------------------------------------------------------------------
*/
function kb_category_delete() {
	NewWindow('','kb_category_popup',700,400,'YES');
	form2.exportera.value = 'delete';
	form2.submit();
}

function kb_category_add() {
	NewWindow('','kb_category_popup',700,400,'YES');
	form2.exportera.value = 'add';
	form2.submit();
}

function kb_category_edit() {
	NewWindow('','kb_category_popup',700,400,'YES');
	form2.exportera.value = 'edit';
	form2.submit();
}

function kb_category_suppliers() {
	NewWindow('','kb_category_popup',700,400,'YES');
	form2.exportera.value = 'suppliers';
	form2.submit();
}

/*
-------------------------------------------------------------------------------
*/


/*
PDF Engine window 
-------------------------------------------------------------------------------
/*
This function is for deleting selected PDF tasks
open include_create_pdfbatch.php with parameters from pdfgeneration.php (m=delete)	
*/

function pmp_pdfengine() {
	//alert('pdf');
  //NewWindowMax('pdfgeneration.php?are='+selectedSurvey+'&eKey='+encryptedKey,'minisurvey_pdfengine',1000,650,'NO');
  window.location = 'pdfgeneration.php?are='+ selectedSurvey+'&eKey='+encryptedKey;
}



/*
Main window / Survey tab
-------------------------------------------------------------------------------
*/
function Sort(sortby, order, page) {
	window.location.href='ST_settings.php?sort='+sortby+'&order='+order+'&m='+page;
}
/*
-------------------------------------------------------------------------------
*/

/*
Main window / User tab 
-------------------------------------------------------------------------------
*/

function Sort_user(sortby, order) {
	window.location.href='ST_settings.php?sort_user='+sortby+'&order_user='+order+'&m='+page;
}
/*
-------------------------------------------------------------------------------
*/


/*
PDF Engine window 
-------------------------------------------------------------------------------
*/
function Sort_pdfbatch(sortby, order) {
	//window.location.href='ST_settings.php?sort_pdfbatch='+sortby+'&order_pdfbatch='+order+'&m='+page;
}
/*
-------------------------------------------------------------------------------
*/



/*
Main window / Survey tab -------------------------------------------------------------------------------
*/
function Select_topmenu(action) {
	alert("Please select something from the list...");
}
/*
-------------------------------------------------------------------------------
*/

/*
Function used for calling the action when topmenu buttons are pressed from respective modules. This fucntion is basically read 
-------------------------------------------------------------------------------
*/
function Subm(action,currentSelected,currentKey,surveytitle) {	

	//Admin section (admin.js)
	if(action == 'deleted_surveys') {
		window.location.href='./?m=5';
		return false;
	}
	else if(action == 'action_log') {
		window.location.href='./?m=5&a=1';
		return false;
	}
	
	
    else if(action == 'new') {
		pmp_create();
		return false;
	}
	else if(action == 'user_new') {
		PMP_user_new();
		return false;
	} 
	else if(action == 'account_new') {
		PMP_account_new();
		return false;
	} 

	//KB Supplier
	else if(action == 'kb_supplier_delete') {
		kb_supplier_delete();
		return false;
	}
	
	else if(action == 'kb_supplier_edit') {
		kb_supplier_edit();
		return false;
	}
	
	else if(action == 'kb_supplier_add') {
		kb_supplier_add();
		return false;
	}
	
	else if(action == 'kb_supplier_multi') {
		kb_supplier_multi();
		return false;
	}
	
	else if(action == 'kb_supplier_open') {
		kb_supplier_open();
		return false;
	}
	
	else if(action == 'kb_supplier_logo') {
		kb_supplier_logo();
		return false;
	}
	
	//KB Category
	else if(action == 'kb_category_delete') {
		kb_category_delete();
		return false;
	}
	
	else if(action == 'kb_category_edit') {
		kb_category_edit();
		return false;
	}
	
	else if(action == 'kb_category_add') {
		kb_category_add();
		return false;
	}
	
	else if(action == 'kb_category_suppliers') {
		kb_category_suppliers();
		return false;
	}
	

// -------------------------------------------
// Ensure 1 option is selected

	if(last_selected == null && !currentSelected) {
		Select_topmenu(action);
		return false;
		}
// -------------------------------------------
	
// Fixes security issues concerning users who don't have access
if(last_selected){
	  var tempString =last_selected.value;
	  var tempArray = tempString.split(":");
	  var tempSelectedSurvey = tempArray[0];
	  var tempAuthorizeString = (tempArray[1] != null) ? tempArray[1] : 'FFF'; // 0= design, 1 = responses, 2 = report
	
	  tempAuthorizeString = ( tempAuthorizeString == 'HIGH' ) ? 'TTT' : tempAuthorizeString; 
	  tempAuthorizeString = ( tempAuthorizeString == 'MEDIUM' ) ? 'FTT' : tempAuthorizeString; 
	  tempAuthorizeString = ( tempAuthorizeString == 'LOW' ) ? 'FFT' : tempAuthorizeString; 
}

  selectedSurvey = (currentSelected)?currentSelected:tempSelectedSurvey;
  authorizeString = tempAuthorizeString;
  encryptedKey = (currentKey)?currentKey:tempArray[2];

// END *** Security fix


	if(action == 'deletecheckedcode') { //created by Tianyao Liu
		deletechecked();
		return false;
	} 
	
	else if(action == 'pdfengine') {
		pmp_pdfengine();
		return false;
	}

	else if(action == 'design') {
		pmp_design();
		return false;
	}
	else if(action == 'preview') {
		pmp_preview();
		return false;
	}
	else if(action == 'report') {
		pmp_report();
		return false;
	}
    else if (action == 'report_distribution')
    {
        pmp_reportdistribution();
        return false;
    }
    else if (action == 'surveys')
    {
        pmp_surveys();
        return false;
    }
	else if(action == 'responses') {
		pmp_responses();
		return false;
	}
	else if(action == 'mailengine') {
		pmp_mail();
		return false;
	}
	else if(action == 'share') {
		pmp_share();
		return false;
	}
	else if(action == 'copy') {
		pmp_create(true);
		return false;
	}
	else if(action == 'delete') {
		pmp_delete(surveytitle);
		return false;
	}
	else if(action == 'weblink') {
		generate_weblink();
		return false;
	}
	else if(action == 'user_info') {
		PMP_user_view();
		return false;
	}
	else if(action == 'user_edit') {
		PMP_user_edit();
		return false;
	}
	else if(action == 'user_delete') {
		PMP_user_delete();
		return false;
	}
	else if(action == 'account_edit') {
		PMP_account_edit();
		return false;
	}
	else if(action == 'account_delete') {
		PMP_account_delete();
		return false;
	}
	else if(action == 'grouplink'){
		window.location = 'grouplink.php?are='+ selectedSurvey+'&eKey='+encryptedKey;
		return false;
	}
alert(action);

}
/*
-------------------------------------------------------------------------------
*/

/*
Main window / Survey tab -------------------------------------------------------------------------------
*/
function generate_weblink() {
	//NewWindow3('generate_weblink.php?are='+selectedSurvey,'minisurvey_dialog',10,10,'NO');
	$.post("surveys_save.php",{'i_micpnumber':(micpnumber)?micpnumber:selectedSurvey,'eKey':(eKey)?eKey:encryptedKey,'action':'get_survey_weblink'},function(data){																				   
		window.location.href='mailto:?Subject=Survey Weblink&body=The URL to the survey is: '+data;			
	});//end .post		
	
}
/*
-------------------------------------------------------------------------------
*/

/*
Shared javascript function that enables the left column bar to appear and saves the settings in ST_settings.php. This function is mainly used in all the 6 modules. 
-------------------------------------------------------------------------------
*/
function Hide(action,pagename,are,subpage,eKey) {
	window.location.href='ST_settings.php?left='+action+'&m='+page+'&pn='+pagename+'&are='+are+'&sp='+subpage+'&eKey='+eKey;
}
/*
-------------------------------------------------------------------------------
*/


/*
Controls the drop-down menu. The option of the drop-down menu is saved into the database
-------------------------------------------------------------------------------
*/
function Set(what, oObj, page) {
	window.location.href='ST_settings.php?'+ what +'=' + oObj.value+'&m='+page;
}
/*
-------------------------------------------------------------------------------
*/

//Category & Multi

function checkCodeExist(table,code,codeClass){
	
	//don't bother if it's not the code
	if($(code).hasClass(codeClass)==false && $(code).hasClass('new_code')==false){
		return false;
	}
	
	
	$('body').data('code_exist',false);
	
	$(table).find("."+codeClass).each(function() {
		if($.trim($(this).val()) == $.trim($(code).val()) && $(this).attr('id')!=$(code).attr('id')){	
			$('body').data('code_exist',true);
			// breakout
			return false;
		}
	});
	
	if($('body').data('code_exist'))
		return true;
	
	return false;
}

//Following code select the survey and hightlights the row if there is only 1 survey in survey listing. chkbox_id is defined in
//survyelist page.
if (typeof chkbox_id != "undefined")
	setBackground (document.getElementById (chkbox_id));

/*
Jquery Ajax Queue
*/
(function($) {
  // jQuery on an empty object, we are going to use this as our Queue
  var ajaxQueue = $({});
  $.ajaxQueue = function(ajaxOpts) {
	var oldComplete = ajaxOpts.complete;
	ajaxQueue.queue(function(next) {
	  ajaxOpts.complete = function() {
		if (oldComplete) oldComplete.apply(this, arguments);
		next(); // run the next query in the queue
	  };  
	  // run the query
	  $.ajax(ajaxOpts);
	});
  };
})(jQuery);


