var survey1 = "";

function getNewWin (l) {
// test to see if this is a form submission that requires a form check first
	if (l) {	
		// alert("so far ...");
		if (!formCheck(l)) return;
		// alert("so good ...");
	}
// else continue if not a form check or if the form check returns not false (true)	
	var h = screen.height; // Get the height of the screen
	var win_height = h - 80; // leave some room for offset
	var branch_id="";
	var survey_id="";
	var lert="";
	
	for (i=0; i<document.theSurvey.branch_id.length; i++) {
		if(document.theSurvey.branch_id.options[i].selected) {
			branch_id = document.theSurvey.branch_id.options[i].value;
			break;
		}
	}
	if (branch_id=="") lert=lert+ccConv(swtchBr(l));	
	
	survey_id = document.theSurvey.survey_id.value;
	if (survey_id=="") lert=lert+ccConv(swtchVer(l));	
	if (lert!="") {
		alert(lert);
		return;
	}	
	var loc_id = l;
	var url = 'dsurvey.php?branch_id=' + branch_id + '&survey_id=' + survey_id + '&loc_id=' + loc_id;
	survey1 = window.open(url,'survey','width=745,height='+win_height+',left=2,top=2,screenX=2,screenY=2,scrollbars=yes,status=no');
	if (window.opener && !window.opener.closed) window.close(); 
	else history.go(-1);
}

//***********
// Required functions used throughout this code to handle browser specific dependencies
//***********

// Functional equivalent to getElementById for IE4 browsers

function IE4GetElementById(id) {
   return document.all[id];
}

// Functional equivalent to getElementById for NN4 browsers
function NN4GetLayerById(id)  {
	for (var i = 0; i < document.theSurvey.elements.length; i++) {
		if (document.theSurvey.elements[i].name && id == document.theSurvey.elements[i].name) return document.theSurvey.elements[i];
	}
}

// test browser to set appropriate equivalent to getElementById
if (document.layers)
   document.getElementById = NN4GetLayerById;
else if (document.all && !document.getElementById)
   document.getElementById = IE4GetElementById;

//***********
// Parameters used for color hinting the questions as the user navigates through the survey
//*********** 
	var origColor = 'black';
	var alrtColor = '#E24D0B';
	var fadeColor = 'gray';  
	var overColor = 'brown';
	var doneColor = 'darkgray';
	var wasThis = origColor;
// the following values are more likely to vary, depending on the style preferences for the installation
	var btnColor = '#FFD834';
	var bkgColor = 'white';
	var taColor = "#EEEEEE";
    var LowBgColor='#ffc020';			// Background color when mouse is not over
	var LowSubBgColor='#ffc020';			// Background color when mouse is not over on subs

//****************
// The following functions control the styles used on various questions and their options 
// depending on the current status of a question (is it answered, active, skipped, new, etc.)
//****************

function switchOn(x) {
	wasThis = x.style.color;
	if (wasThis==fadeColor) x.style.color=doneColor;
	else x.style.color=overColor;
}

function switchOff(x) {
	x.style.color=wasThis;
}

function chkPrev(x) {
	var y = parseInt(getID(x, 'q'))
	for (i=0; i<Qarray.length; i++) {
//		alert(i + " " + y);
		if (Qarray[i]==y) { 
			var z = i;
			break;
		}
	}

//	for (i=startQ; i<y; i++) {
	for (i=0; i<z; i++) {
		var c = 'q' + i;
		if (document.getElementById(c).style.color!=fadeColor)
		document.getElementById(c).style.color = alrtColor;
	}
}

function getIndex(input) {
 	var index = -1, i = 0, found = false;
	while (i < document.theSurvey.elements.length && index == -1)
		if (document.theSurvey.elements[i] == input)index = i;
		else i++;
	return index;
}

function restoreDefault(StypeItem) {   
	for (var i = 0; i < StypeItem.length; i++) {     
		 if (StypeItem.options[i].defaultSelected == true) {        
		 StypeItem.options[i].selected=true      }   
	}
}

function getID(qname,bg) {
	s=qname.indexOf(bg) + bg.length;
	e=qname.indexOf("_",s);
	if (e<0) e=qname.length;
	// alert("S: " + s + " E: " + e + " Name: " + qname + "_");
	return qname.substring(s,e);
}

function setRadioButtons(it,rb) {
	it.style.color=fadeColor;
	var y = parseInt(getID(rb, 'q'))
	for (i=0; i<Qarray.length; i++) {
		if (Qarray[i]==y) { 
			var x = 'q' + i;
			break;
		}
	}
	document.getElementById(x).style.color = fadeColor;
	wasThis = fadeColor;
   	chkPrev(rb);
	// check 'part' number 3 (n/a) for this question to see if already set
	whereIs = rb.indexOf("p");
	cb = rb.substring(0,whereIs+1);
	cb = cb + "3";
	cbFld = eval("document.theSurvey." + cb);
	if (cbFld) {
	 	if (cbFld.checked) {
			it.checked=false;
			return;	
		}
	}
	//	setFld= enum("opener.document.theSurvey." + rb);
	//	setFld.value = it.value;
	if (document.all || document.getElementById) {
		var btn=eval("document.theSurvey." + rb);
   		var x = btn.length;
   		for (var i=0; i<x; i++) {
   			if (btn[i].checked) btn[i].style.backgroundColor=btnColor;
  			else btn[i].style.backgroundColor=bkgColor;
   		}
   	}
    // loops to ensure that all radio button type question parts for current questionID
    // are selected, and then can 'fade' the related question text cell
    // if partNo > 1 then loop down the index of elements first else just loop up
   	var doFade=1;
   	var qIndex=getIndex(it);
   	var questionID=parseInt(getID(rb,"q"));
	var partNO = parseInt(getID(rb,"p"));
    if (partNO>1) {
       for (var j=qIndex-1; j>-1; j--) {
            prevElement=document.theSurvey.elements[j];
            prevQ=prevElement.name;
            if (questionID == parseInt(getID(prevQ,"q"))) {
            	prevT=prevElement.type;
            	if (prevT=="radio" && prevElement.checked) doFade++;
            } else break;
        }
     }
     // now do forward loop to checked items in other 'parts' of the same questionID
	 totalElements=it.form.length;
     for (var i=qIndex+1; i<totalElements; i++) {         		       	
        nxtElement=document.theSurvey.elements[i];
        nxtQ=nxtElement.name;
        if (questionID == getID(nxtQ,"q")) {
            nxtT=nxtElement.type;
            if (nxtT=="radio" && nxtElement.checked) doFade++;
        } else break;
    }   	
   	if (doFade>1) {
		// fade the question text cell if all Radio Button 'parts' of a question are completed
		var x = 'q' + questionID;
		document.getElementById(x).style.color = fadeColor;
   		chkPrev(rb);
	}
}

function setCheckButtons(it,cb) {
	if (it.checked) {
		it.style.color=btnColor;
		var y = parseInt(getID(cb, 'q'))
	for (i=0; i<Qarray.length; i++) {
		if (Qarray[i]==y) { 
			var x = 'q' + i;
			break;
		}
	}
		document.getElementById(x).style.color = fadeColor;
		wasThis = fadeColor;
		chkPrev(cb);
	}	else it.style.color=bkgColor;
	// check if it's an Applicable -- Not/Applicable checkbox
	if (cb.indexOf("_a")<0) return;
	else {
		totalElements=it.form.length;
		if (it.checked) {
   			it.style.backgroundColor=btnColor;
			qIndex=getIndex(it);
   			questionID=getID(cb,"q");
			partNO = getID(cb,"p");
            // loops to uncheck radio buttons for the current questionID
            // and dim those previous fields
            // if partNo > 1 then loop down the index of elements first else just loop up
            if (partNO>1) {
            	for (j=qIndex-1; j>-1; j--) {
            		prevElement=document.theSurvey.elements[j];
            		prevQ=prevElement.name;
            		if (questionID == getID(prevQ,"q")) {
            			prevT=prevElement.type;
            			if (prevT=="radio" && prevElement.checked) {
            				prevElement.checked=false;
            				prevElement.style.backgroundColor=bkgColor;
            			}
            		} else break;
            	}
            }
            // now do forward loop to reset checked items for the same questionID
            for (i=qIndex+1; i<totalElements; i++) {         		       	
            		nxtElement=document.theSurvey.elements[i];
            		nxtQ=nxtElement.name;
            		if (questionID == getID(nxtQ,"q")) {
            			nxtT=nxtElement.type;
            			if (nxtT=="radio" && nxtElement.checked) {
            				nxtElement.checked=false;
            				nxtElement.style.backgroundColor=bkgColor;
            			}
            		} else break;
              }
  			// loop to restore default settings?
  		}
   	}  	
}

function setSelectItem(it,sl) {
	var slist=eval("document.theSurvey." + sl);
	var y = parseInt(getID(sl, 'q'))
	for (i=0; i<Qarray.length; i++) {
		if (Qarray[i]==y) { 
			var x = 'q' + i;
			break;
		}
	}
   if (slist.selectedIndex && slist.selectedIndex!=0) {
		document.getElementById(x).style.color=fadeColor;
		wasThis = fadeColor;
		slist.options[slist.selectedIndex].style.color=fadeColor;
	} else {
		document.getElementById(x).style.color=alrtColor;
		//	wasThis = alrtColor;
	}	 
	chkPrev(sl);
}

//*********
// the following routines are used strictly for debugging purposes
//*********

function viewValues() {
	var alrtVar = "";
	for (var i=0; i < document.theSurvey.length; i++) {
		alrtVar = " | " + document.theSurvey.options[i].name + ": " + document.theSurvey.options[i].value;
	}
	alert(alrtVar);	
}

function validate(f) {
	for (var i=0;i<f.length;i++)
	{
		current = f.elements[i];
		if (current.type=="radio") {
			alert(current.name + "[" + i + "]: " + current.checked);
		}
	}
}

function gotoCustomerURL (tURL,tMail,rURL,rMail,rlocID,oname,ourl) {
	var h = screen.height; // Get the height of the screen
	var win_height = h - 80; // leave some room for offset
	var w = screen.width; // Get the width of the screen
	var win_width = w - 80; // leave some room for offset
	var url = tURL + '?url=' + rURL + '&email=' + rMail + '&to=' + tMail + '&loc=' + rlocID + '&on=' + oname + '&ou=' + ourl;
	survey1 = window.open(url,'Library','left=6,top=6,width=745,height='+win_height+',screenX=6,screenY=6,scrollbars=yes,status=no');
	window.close(); 
}

function formCheck(l) {
//	Form Check to validate that user has selected a choice in all select lists

var brnch = true;
var srvy = true;
var lert="";
	
	if(document.theSurvey.branch_id.options[0].selected && document.theSurvey.branch_id.length>1) {
//		alert("Location check: " + document.theSurvey.branch_id.length);
		lert=lert + "\n" + swtchBr(l) + "\n";
		document.theSurvey.branch_id.focus();
		brnch = false;
	}
	   
// no need to check survey select options

// return setting
	if (brnch && srvy) return true;
	alert(lert);
	return false;
} 

function swtchBr(l) {
	switch (l) {
		case 'fr_CA': 
			return ("Veuillez indiquer l’emplacement/succursale!\n\n"); 
			break;
		case 'es': 
			return ("Indique el centro/la sucursal!\n\n"); 
			break;
		case 'zh_CN':
			return ("\u8BF7\u6807\u660E\u5728\u54EA\u4E00\u5BB6\u56FE\u4E66/\u9986\u5206\u9986\n\n");	
			break;	
		case 'zh_HK':
			return ("\u8ACB\u6A19\u660E\u5728\u54EA\u4E00\u5BB6\u5716\u66F8/\u9928\u5206\u9928\n\n");	
			break;		
		case 'pa_PK':
			return ("\u0A15\u0A3F\u0A30\u0A2A \u0A3E\u0A15 \u0A30\u0A15 \u0A47\u0A38\u0A25\u0A3E/ \u0A28\u0A2C\u0A30\u0A3E\u0A02 \u0A1A\u0A26 \u0A3E\u0A28\u0A3E \u0A2E\u0A26\u0A71\u0A38\u0A4B\n\n");
			break;		
		case 'ru':
			return ("\u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442, \u0430\u0443\u043A\u0430\u0436\u0438\u0442 \u0435\u043C\u0435\u0441\u0442 \u043E\u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438 / \u044F\u0444\u0438\u043B\u0438\u0430 \u043B\u0431\u0438\u0431\u043B\u0438\u043E\u0442\u0435\u043A\u0438\n\n");
			break;		
		default: return ("Please indicate the Location/Branch!\n\n");
	}
}

function swtchVer(l) {
	switch (l) {
	   	case 'fr_CA': 
	   		return ("Veuillez indiquer la version du sondage!\n\n"); 
	   		break;
	   	case 'es': 
	   		return ("Indique la versión de la encuesta!\n\n"); 
	   		break;
		case 'zh_CN':
			return ("\u8BF7\u6807\u660E\u9009\u7528\u54EA\u4E00\u7248\u672C\u7684\u8C03\u67E5\u95EE\u5377\n\n");	
			break;	
		case 'zh_HK':
			return ("\u8ACB\u6A19\u660E\u9078\u7528\u54EA\u4E00\u7248\u672C\u7684\u8ABF\u67E5\u554F\u5377\n\n");	
			break;			   	
		case 'pa_PK':
	   		return ("\u0A15\u0A3F\u0A30\u0A2A \u0A3E\u0A15 \u0A30\u0A26\u0A71\u0A38 \u0A4B\u0A38\u0A30\u0A35\u0A47\u0A16 \u0A23\u0A26 \u0A3E\u0A30\u0A42\u0A2A\u0A3E\u0A02\u0A24 (Version) \u0A30\u0A15\u0A3F\u0A39\u0A5C \u0A3E\u0A39\u0A48\n\n"); 
	   		break;
		case 'ru':
	   		return ("\u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442, \u0430\u0443\u043A\u0430\u0436\u0438\u0442 \u0435\u0432\u0435\u0440\u0441\u0438 \u044E\u043E\u043F\u0440\u043E\u0441\u0430\n\n"); 
	   		break;
	   	default: return ("Please indicate the Version of the survey!\n\n");
	}
}
function pzChk(pz) {
	pre = /^\s*[a-ceghj-npr-tvxy]\d[a-z](\s)?\d[a-z]\d\s*$/i; //Cdn postal code
	zre1 = /^\D*(\d{5})$/; // regular sip
	zre2 = /^\D*(\d{5})\D*(\d{4})\D*$/; // zip+4 version
	if (!pz || pz=='') return true;
	if (pre.test(pz) || zre1.test(pz) || zre2.test(pz)) return true;
	else return false;
}
function emChk(e) {
  	var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
  	var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/; // valid
    if (!e || e=='') return true;
  	if (!reg1.test(e) && reg2.test(e)) return true;
	else return false;
}
function ccConv(str) {
	if (str.CharAt(0)=='&') return str;
	var n = '';
	for (i=0; i<=str.length; i++) {
		n = n + charCodeAt(str.charAt(i));
	}
	return n;
}

document.cookie = "dSurvey=1";

function instructions_popup() {
	reWin=window.open('http://www.countingopinions.com/instructions/cookies.htm#<? echo $loc_id; ?>','','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=800,height=600,top=1,left=1')
}

function dLoader(l) {
	window.focus();
	if (!document.cookie) {
		switch (l) {
	   		case 'fr_CA': 
	   			where_to = confirm("Votre navigateur doit être configuré pour permettre les cookies de session avant que vous puissiez répondre à l'aperçu.\n\nOK de Click pour des instructions sur configurer votre annulation autrement choisie, de navigateur pour continuer."); 
	   		case 'es': 
				where_to = confirm("Nuestro browser se debe configurar para permitir las cookies de la sesión antes de que puedas responder al examen.\n\nChascar MUY BIEN (Ok) para las instrucciones en el configuración de tu Browser,\nsi no seleccionar la cancelación (Cancel) para continuar.");
			case 'zh_CN':
				where_to = confirm("cookie &#21151;&#33021;&#34987;&#20572;&#27490;");	
			case 'zh_HK':
				where_to = confirm("cookies &#34987;&#23553;&#37782;");	
			case 'pa_PK':
	   			where_to = confirm("&#2596;&#2625;&#2617;&#2622;&#2593;&#2631; &#2581;&#2626;&#2581;&#2624;&#2588;&#2620; &#2566;&#2607;&#2635;&#2583; &#2588;&#2622;&#2602;&#2598;&#2631; &#2617;&#2600;&#2404;"); 
			case 'ru':
	   			where_to = confirm("&#1042;&#1072;&#1096; &#1073;&#1088;&#1072;&#1091;&#1079;&#1077;&#1088; &#1085;&#1077; &#1087;&#1088;&#1080;&#1085;&#1080;&#1084;&#1072;&#1077;&#1090; cookies"); 
	   		default: where_to = confirm("Your browser must be configured to allow Session Cookies\n before you will be able to respond to the Survey.\n\nClick OK for instructions on configuring your Browser,\n otherwise select Cancel to continue.");
		}
		if (where_to) instructions_popup();
	} else {
		var kill_time = new Date("January 1, 1970");
		var kill_string = "dSurvey=1;expires=" + kill_time.toGMTString();
		document.cookie = kill_string;
	}
}

function dpzemChk(f,l) {
	if ((!pzChk(f.postal_code.value) && !confirm(swtchConfrmpz(l))) || (!emChk(f.respondent_email.value) && !confirm(swtchConfrmem(l)))) return false;
	else return true;
}
function ccConv(str) {
	return str.replace(/&#(\d+);/g, function (search, match) { return "\\u" + parseInt(match, 10).toString(16); });
	//if (str.CharAt(0)=='&') return str;
	//var n = '';
	//for (i=0; i<=str.length; i++) {
	//	n = n + charCodeAt(str.charAt(i));
	//}
	//return n;
}