﻿//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;
    }
}

// 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());
    }
}

/*|||||||||| 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);
    
    var oLSID = document.getElementById('leadsourceid');
    
    //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)
    {        
        //alert(oLSID.value);
        switch(oLSID.value)
        {
            //prevent Channel/Event leads from adding default option for specialzation field
            case '1052':
            case '1053':
                //alert(objTarget.id);
                if(objTarget.id != 'specialization')
                    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] = new Option(aryItem[0], aryItem[1]);
                    //set the title attribute for each item
			        objTarget.options[j].setAttribute('title', aryItem[0]);
                    
                    //alert(objTarget.options[j + 1].text);
                    
                    if(objTarget.options[j].text == 'Undecided')
                        objTarget.options[j].selected = true;
                }
                break;
            default:
                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;
                }
                break;
        }
        
        objTarget.disabled = false;
    }
}

/*|||||||||| FORM SPECIFIC FUNCTIONALITY ||||||||||*/

function checkZip(strZip)
{
	if(strZip.length > 4)
	{
		dataIslandProxy.GetStateCountryByZip(strZip, checkZipSucceeded);
	}
	else
	{
		//not a valid USA/CAN zip based on format, don't bother doing ajax call
		toggleFields('show');
	}
}

function checkZipSucceeded(result, eventArgs)
{	
	var response = result.split('-');
	if(response[0] == 0)
	{
		//not a valid USA/CAN zip
		toggleFields('show');
	}
	if(response[0] == 1)
	{
		//valid USA zip
		toggleFields('hide', response[1]);
		frm.country_code.value = "USA";		
	}
	if(response[0] == 2)
	{
		//valid CAN zip
		toggleFields('hide', response[1]);
		frm.country_code.value = "CAN";
	}
}

function toggleFields(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";
		
		//not all forms have the errorUl functionality
		if(document.getElementById("errorUl"))
		{
			//if zip had an error previously, remove errorField class name from question cell
			if(frm.zip.parentNode.parentNode.childNodes[0].className.indexOf("errorField") > -1)
				frm.zip.parentNode.parentNode.childNodes[0].className = frm.zip.parentNode.parentNode.childNodes[0].className.replace("errorField", "");
			//also remove error text from list of errors
			if(document.getElementById("errorUl").innerHTML.indexOf("<li>Please enter your zip/postal code.</li>") > -1)
				document.getElementById("errorUl").innerHTML = document.getElementById("errorUl").innerHTML.replace("<li>Please enter your zip/postal code.</li>", "");
		}
	}
	else if(action == "show")
	{
		//reset state value & hide
		frm.state_code.value = "";
		document.getElementById("stateRow").className = "hidden";
		
		//if the phone country code field exists, reset value & show
		if(frm.phone_country_code)
		{
			frm.phone_country_code.value = "";
			document.getElementById("phoneCountryCodeRow").className = "visible";
		}
		
		//if the country code field exists, reset value & show
		if(frm.country_code)
		{
		    frm.phone_country_code.value = "";
			document.getElementById("countryRow").className = "visible";
		}
	}
}

//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('hide');
	}
	if(response[0] == 1)
	{
		//valid USA zip
		frm.country_code.value = "USA";
		toggleFieldsAlt('show', response[1]);		
	}
	if(response[0] == 2)
	{
		//valid CAN zip
		frm.country_code.value = "CAN";
		toggleFieldsAlt('show', response[1]);
		
	}
}

function toggleFieldsAlt(action, state)
{
	if(action == "hide")
	{
		frm.country_code.value = "";
		frm.state_code.value = "";
		//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";
		}

		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";
		}
	}
}

//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