﻿//global variable
var dataIslandProxy;
var frm = document.forms[0];

// Initializes global and proxy default variables.
function pageLoad()
{
    // Instantiate the service proxy.
    dataIslandProxy = new CW35.WebServices.DataIslands.DataIslands();
    
    dataIslandProxy.set_defaultFailedCallback(FailedCallback);
}

/*|||||||||| STANDARD DROPDOWN BEHAVIOR (ALL DROP DOWN FIELDS REQUIRED) ||||||||||*/

//Initial function call from web page
function LoadLevel1Data(targetId, isEndLevel)
{
    var oLSID = document.getElementById('leadsourceid');
//    alert('in onloadlevel 001');
//    alert(targetId);    
//    alert(oLSID.value);
    dataIslandProxy.GetLevel1JSONData(oLSID.value, targetId, isEndLevel, LoadLevelDataSucceeded);
}

function LoadLevel2Data(callerID, targetId, isEndLevel)
{
    var oLSID = document.getElementById('leadsourceid');
    var oCaller = document.getElementById(callerID);
    var oTarget = document.getElementById(targetId);
//    alert('in onloadlevel 002');
//    alert(targetId);    
//    alert(oLSID.value);
    
    //if the option selected in the level above this one is blank, clear this drop down and disabled it
    if(oCaller[oCaller.selectedIndex].value == '' || oCaller[oCaller.selectedIndex].value == null || oCaller[oCaller.selectedIndex].value.length < 0)
    {
        for(var i = oTarget.options.length; i >= 0; i--)
        {	        
	        oTarget.options[i] = null;
        }        
        oTarget.options[0] = new Option('Select one', '');   
        oTarget.options[0].selected = true;     
        oTarget.disabled = true;
    }
    else
    {
        dataIslandProxy.GetLevel2JSONData(oLSID.value, oCaller[oCaller.selectedIndex].value, targetId, isEndLevel, LoadLevelDataSucceeded);
    }
}

function LoadLevel3Data(level1CallerID, level2CallerID, targetId, isEndLevel)
{
    var oLSID = document.getElementById('leadsourceid');
    var oCallerLevel1 = document.getElementById(level1CallerID);
    var oCallerLevel2 = document.getElementById(level2CallerID);
    var oTarget = document.getElementById(targetId);
//    alert('in onloadlevel 003');
//    alert(targetId);    
//    alert(oLSID.value);
    
    //if the option selected in the level above this one is blank, clear this drop down and disabled it
    if(oCallerLevel2[oCallerLevel2.selectedIndex].value == '' || oCallerLevel2[oCallerLevel2.selectedIndex].value == null || oCallerLevel2[oCallerLevel2.selectedIndex].value.length < 0)
    {
        for(var i = oTarget.length; i >= 0; i--)
        {
	        oTarget.options[i] = null;
        }        
        oTarget.options[0] = new Option('Select one', '');        
        oTarget.disabled = true;
    }
    else
    {
        dataIslandProxy.GetLevel3JSONData(oLSID.value, oCallerLevel1[oCallerLevel1.selectedIndex].value, oCallerLevel2[oCallerLevel2.selectedIndex].value, targetId, isEndLevel, LoadLevelDataSucceeded);
    }
}

// Callback function that
// processes the service return value.
function LoadLevelDataSucceeded(result, eventArgs)
{
//    alert ('in success');
//    alert (result);
    
    //parse the JSON string result into usable JavaScript objects
    objResult = result.parseJSONStr();
//        alert(objResult.target);
//        alert('++' + objResult.retVal + '++');

    //setup objects
    var objTarget = document.getElementById(objResult.target);
    var strAry = objResult.retVal.toString();
    
    //clear the drop down in prep for population
    for(var i = objTarget.length; i >= 0; i--)
    {
	    objTarget.options[i] = null;
    }
    
    //populate the drop down
    if(objResult.retVal.length > 0)
    {        
        objTarget.options[0] = new Option('Select one', '');
        
        for(var j = 0; j < objResult.retVal.length; j++)
        {   
            var aryItem = new Array();
            aryItem = objResult.retVal[j].split("|");
        
            objTarget.options[j + 1] = new Option(aryItem[0], aryItem[1]);
            //set the title attribute for each item
			objTarget.options[j + 1].setAttribute('title', aryItem[0]);
        }
        
        objTarget.disabled = false;
    }
    //if level 2 dropdown's id is "program_code" and v is present in QS
    //filter the degree list down to a subset of degrees using filterDegrees function
    var qs = new Querystring();
    if(objTarget.id == "program_code" && qs.get("v") != null)
    {
			switch(qs.get("v").toLowerCase())
			{
				//only these 3 landing pages get filtered lists of degrees
				case "phd":
				case "masters":
				case "bachelors":
					filterDegrees(qs.get("v").toLowerCase());
					break;
				default:
					break;
			}
		}
}

// Callback function invoked when a call to 
// the  service methods fails.
function FailedCallback(error, userContext, methodName) 
{
    if(error !== null) 
    {
        alert("An error occurred: " + error.get_message());
    }
}

function filterDegrees(landingPage)
{
	var arrValidDegrees = new Array();
	switch(landingPage.toLowerCase())
	{
		case "phd":
			arrValidDegrees = [890, 891, 1014, 850, 416, 921, 417, 418, 419, 894, 1007, 744, 404, 745, 406, 405, 407, 408, 881, 1006, 409, 410, 412, 413, 414, 415, 1005, 851, 885, 892, 893, 1003, 421, 420, 422, 1004, 856, 858, 857, 411, 1041, 746, 852, 1001, 1000, 1410];
			break;
		case "masters":
			arrValidDegrees = [890, 891, 1014, 1025, 1026, 1023, 1021, 1027, 1032, 1031, 1030, 1029, 1028, 1024, 1022, 1020, 1018, 1017, 1016, 1019, 674, 366, 352, 740, 899, 742, 367, 743, 1013, 387, 388, 389, 390, 1012, 370, 939, 371, 372, 368, 373, 353, 374, 429, 622, 378, 1011, 380, 379, 938, 382, 383, 384, 385, 898, 623, 1035, 1403, 1404, 398, 895, 399, 400, 431, 432, 1009, 430, 392, 393, 883, 394, 395, 884, 882, 1034, 396, 397, 1010, 896, 897, 1036, 853, 855, 854, 642, 1037, 850, 416, 921, 417, 418, 419, 894, 1007, 744, 404, 745, 406, 405, 407, 408, 881, 1006, 409, 410, 412, 413, 414, 415, 1005, 851, 885, 892, 893, 1003, 421, 420, 422, 1004, 856, 858, 857, 411, 1041, 746, 852, 1001, 1000, 1405, 1406, 1407, 1408, 1409, 1410];
			break;
		case "bachelors":
			arrValidDegrees = [673, 351, 360, 357, 359, 358, 877, 901, 1038, 361, 362, 878, 741, 363, 1402, 364, 879, 1040, 880, 900, 940, 941, 1039];
			case "": 
			break;
		default:
			break;
	}
	var degrees = document.getElementById("program_code");
	//loop through all degrees in current list
	for(var i = degrees.options.length - 1; i > 0; i--)
	{
		var blnValid = false;
		//if degree doesn't exist in arrValidDegrees array, flag it for removal
		for(var j = 0; j < arrValidDegrees.length; j++)
		{
			if(degrees.options[i].value == arrValidDegrees[j])
				blnValid = true;		
		}
		//remove degrees that are flagged invalid
		if(blnValid == false)
			degrees.options[i] = null;
	}
}

/*|||||||||| ALTERNATE DROPDOWN BEHAVIOR (NOT ALL DROP DOWN FIELDS ARE REQUIRED, DEFAULT VALUES ARE PREPOPULATED) ||||||||||*/

//Initial function call from web page
function LoadLevel1DataAndDefault(targetId, isEndLevel)
{
    var oLSID = document.getElementById('leadsourceid');
    //    alert('in onloadlevel 001');
//    alert(targetId);    
//    alert(oLSID.value);
    dataIslandProxy.GetLevel1JSONData(oLSID.value, targetId, isEndLevel, LoadLevelDataSucceeded);
}

function LoadLevel2DataAndDefault(callerID, targetId, isEndLevel)
{
    var oLSID = document.getElementById('leadsourceid');
    var oCaller = document.getElementById(callerID);
    var oTarget = document.getElementById(targetId);
//    alert('in onloadlevel 002');
//    alert(targetId);    
//    alert(oLSID.value);
    
    //if the option selected in the level above this one is blank, clear this drop down and disabled it
    if(oCaller[oCaller.selectedIndex].value == '' || oCaller[oCaller.selectedIndex].value == null || oCaller[oCaller.selectedIndex].value.length < 0)
    {
        for(var i = oTarget.options.length; i >= 0; i--)
        {	        
	        oTarget.options[i] = null;
        }        
        oTarget.options[0] = new Option('Select one', '');   
        oTarget.options[0].selected = true;     
        oTarget.disabled = true;
    }
    else
    {
        dataIslandProxy.GetLevel2JSONData(oLSID.value, oCaller[oCaller.selectedIndex].value, targetId, isEndLevel, LoadLevelDataSucceeded);
    }
}

function LoadLevel3DataAndDefault(level1CallerID, level2CallerID, targetId, isEndLevel)
{
    var oLSID = document.getElementById('leadsourceid');
    var oCallerLevel1 = document.getElementById(level1CallerID);
    var oCallerLevel2 = document.getElementById(level2CallerID);
    var oTarget = document.getElementById(targetId);
//    alert('in onloadlevel 003');
//    alert(targetId);    
//    alert(oLSID.value);
    
    //if the option selected in the level above this one is blank, clear this drop down and disabled it
    if(oCallerLevel2[oCallerLevel2.selectedIndex].value == '' || oCallerLevel2[oCallerLevel2.selectedIndex].value == null || oCallerLevel2[oCallerLevel2.selectedIndex].value.length < 0)
    {
        for(var i = oTarget.length; i <= 0; i--)
        {
	        oTarget.options[i] = null;
        }        
        oTarget.options[0] = new Option('Select one', '');        
        oTarget.disabled = true;
    }
    else
    {
        dataIslandProxy.GetLevel3JSONData(oLSID.value, oCallerLevel1[oCallerLevel1.selectedIndex].value, oCallerLevel2[oCallerLevel2.selectedIndex].value, targetId, isEndLevel, LoadLevelDataAndDefaultSucceeded);
    }
}

// Callback function that
// processes the service return value.
function LoadLevelDataAndDefaultSucceeded(result, eventArgs)
{
//    alert ('in success');
//    alert (result);
    
    //parse the JSON string result into usable JavaScript objects
    objResult = result.parseJSONStr();
//        alert(objResult.target);
//        alert('++' + objResult.retVal + '++');

    //setup objects
    var objTarget = document.getElementById(objResult.target);
    var strAry = objResult.retVal.toString();
    
    //clear the drop down in prep for population
    for(var i = objTarget.length; i >= 0; i--)
    {
	    objTarget.options[i] = null;
    }
    
    //populate the drop down
    if(objResult.retVal.length > 0)
    {        
        objTarget.options[0] = new Option('Select one', '');
        
        for(var j = 0; j < objResult.retVal.length; j++)
        {   
            var aryItem = new Array();
            aryItem = objResult.retVal[j].split("|");
        
            objTarget.options[j + 1] = new Option(aryItem[0], aryItem[1]);
            //set the title attribute for each item
			objTarget.options[j + 1].setAttribute('title', aryItem[0]);
            
            //alert(objTarget.options[j + 1].text);
            
            if(objTarget.options[j + 1].text == 'Undecided')
                objTarget.options[j + 1].selected = true;
        }
        
        objTarget.disabled = false;
    }
}

/*|||||||||| FORM SPECIFIC FUNCTIONALITY ||||||||||*/

//alternate functions for Zip checking because Josh is a jerk
//2008-05-06 Tom Wallace
function checkZipAlt(strZip)
{
	if(strZip.length > 4)
		dataIslandProxy.GetStateCountryByZip(strZip, checkZipSucceededAlt);
	else //not a valid USA/CAN zip based on format, don't bother doing ajax call
		toggleFieldsAlt('hide');
}

function checkZipSucceededAlt(result, eventArgs)
{
	var response = result.split('-');
	if(response[0] == 0)
	{
		//not a valid USA/CAN zip
		toggleFieldsAlt('show');
	}
	if(response[0] == 1)
	{
		//valid USA zip		
		toggleFieldsAlt('hide', response[1]);		
		frm.country_code.value = "USA";
	}
	if(response[0] == 2)
	{
		//valid CAN zip
		toggleFieldsAlt('hide', response[1]);
		frm.country_code.value = "CAN";
		
	}
}

function toggleFieldsAlt(action, state)
{
	if(action == "hide")
	{
		frm.state_code.value = state;
		//not all forms have a phone_country_code field
		if(frm.phone_country_code)
		{
			frm.phone_country_code.value = "1";
			document.getElementById("phoneCountryCodeRow").className = "hidden";
		}
		document.getElementById("countryRow").className = "hidden";
		document.getElementById("stateRow").className = "hidden";
	}
	else if(action == "show")
	{
		frm.state_code.value = state;
		if(frm.phone_country_code)
		{
			frm.phone_country_code.value = "";
			document.getElementById("phoneCountryCodeRow").className = "visible";
		}
		//reveal country question
		if(frm.country_code[frm.country_code.selectedIndex].value == "USA" || frm.country_code[frm.country_code.selectedIndex].value == "CAN")
		{
			document.getElementById("stateRow").className = "visible";		  
			document.getElementById("countryRow").className = "visible";
		}
	}
}

function showValidEdLevels(client_id)
{
	var frm = document.forms[0]
	var degree_id = frm.program_code[frm.program_code.selectedIndex].value;
	if(degree_id != "")
	{
		frm.education_level.disabled = false;
		//strip invalid values from dropdown
		dataIslandProxy.GetValidEdLevelValues(degree_id, client_id, frm.education_level.id, LoadLevelDataSucceeded);
	}
	else
		frm.education_level.disabled = true;
}


function Querystring(qs) { 
	this.params = new Object()
	this.get=Querystring_get
	if (qs == null)
		qs=location.search.substring(1,location.search.length)
	if (qs.length == 0) return
	qs = qs.replace(/\+/g, ' ')
	var args = qs.split('&') 
	for (var i=0;i<args.length;i++) {
		var value;
		var pair = args[i].split('=')
		var name = unescape(pair[0]).toLowerCase();
		if (pair.length == 2)
			value = unescape(pair[1]).toLowerCase();
		else
			value = name.toLowerCase();
		this.params[name] = value.toLowerCase();
	}
}

function Querystring_get(key, default_) {
	if (default_ == null) default_ = null;
	var value=this.params[key]
	if (value==null) value=default_;
	return value
}

//required AJAX functionality
if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

// The following block implements the string.parseJSONStr method
// Augment String.prototype.
(function (s) {
  // Augment String.prototype. We do this in an immediate anonymous function to
  // avoid defining global variables.

  // m is a table of character substitutions.
  var m = {
    '\b': '\\b',
    '\t': '\\t',
    '\n': '\\n',
    '\f': '\\f',
    '\r': '\\r',
    '"' : '\\"',
    '\\': '\\\\'
  };

  s.parseJSONStr = function (filter) {

    // Parsing happens in three stages. In the first stage, we run the text against
    // a regular expression which looks for non-JSON characters. We are especially
    // concerned with '()' and 'new' because they can cause invocation, and '='
    // because it can cause mutation. But just to be safe, we will reject all
    // unexpected characters.

    try {
      if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.
        test(this)) {
          // In the second stage we use the eval function to compile the text into a
          // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
          // in JavaScript: it can begin a block or an object literal. We wrap the text
          // in parens to eliminate the ambiguity.

          var j = eval('(' + this + ')');

          // In the optional third stage, we recursively walk the new structure, passing
          // each name/value pair to a filter function for possible transformation.

          if (typeof filter === 'function') {
            function walk(k, v) {
              if (v && typeof v === 'object') {
                for (var i in v) {
                  if (v.hasOwnProperty(i)) {
                    v[i] = walk(i, v[i]);
                  }
                }
              }
              return filter(k, v);
            }

            j = walk('', j);
          }
          return j;
        }
      } catch (e) {

      // Fall through if the regexp test fails.

      }
      throw new SyntaxError("parseJSONStr");
    };
  }
) (String.prototype);

// Example code to implement above parseJSONStr method:

    //JSONData = '{"color" : "green"}';   // Example of what is received from the server.
    //testObject=JSONData.parseJSONStr();   
    //alert(testObject.color); // Outputs: green