// Move these to the survey for translation
var commentHint = "Enter your comments here.  If you're looking for help, please click on the link below";
var emailHint = "email@example.net";

var _charRemainingTex = "%REMAININGCHAR% characters remaining."; 
var commentValidation = 'minimum 3, maximum ' + _max_chars + ' characters' + "\nPlease enter your comments before you press Submit"; 
var maxLimitMessage = "Sorry, we ran out of space for your message."; 
var emailValidation = "Please re-enter your full email address"; 

var browser = 'UNKNOWN';
var _max_chars = 1000;
var _min_chars = 3;
var debug = false;

var _fid = "0";
var _oid = "";
var _ch = "";
var _lang = "en-US";

var modalLangPageBasePath = "http://aol-clarabridge.vovici.net/ClarabridgeSite/";

// used in submit_form function to prevent multi-submit via rapid multi-clicks
var form_submitted = false;

//These are the hidden field in the Feedback survey
/*
Q5_1 = Theme ID  
Q5_2 = Language ID  
Q5_3 = Preview  
Q5_4 = Thank You Page URL  
Q5_5 = Thank You Page URL With Parameter  
Q5_6 = prop16 Chanel URL Value  
Q5_7 = prop17 auto-generate feedback ID  
Q5_8 = prop18-grab oid URL Value 
Q5_9 = CurrentForm
Q5_10 = referring url
Q5_11 = completed date
Q5_12 = user agent
Q5_13 = browser type
Q5_14 = operating system
Q5_15 = screen resolution
*/

function AlertMessage(message){
	if(message){
		alert(message);
	}
}

function DebugMess(message)
{
	if(debug){
		AlertMessage(message);
	}
}

function page_init()
{
    DebugMess("init is called");
    window.focus();
    
    document.onkeypress = validateOnEnterKey;
    
    // used in submit_form function to prevent multi-submit via rapid multi-clicks
    document.forms[0].onsubmit = submit_form;

    initHintTextboxes();

    if(typeof _currentForm != "undefined"){
         if(_currentForm == "FeedbackForm"){
            SetElementValue('Q5_15', screen.width + ' x ' + screen.height);
            GetPipedValues();
            //call the aol omniture script
            GetFeedbackFormOmnitureCode(_ch, _fid, _oid);
         }
    }
    
    var obj1 = document.getElementById('feedback_form');
    var obj2 = document.getElementById('thank_you_form');
  
    if(obj1){ obj = obj1; }
    else if(obj2){ obj = obj2; }
    
    if (obj && window.name != "")
    {
        //IF NOT BOOKMARKED, RESIZE THE WINDOW AND DISPLAY CLOSE BUTTONS.
        try { 
		    var e = document.getElementById('cancel_button');
		    if (e) e.style.display = 'block'; 
	    }
        catch(e) { 
            /* Error */ 
        }

		var width = document.documentElement.clientWidth;
		var height = document.documentElement.clientHeight;
		
        var adjust_width = obj.offsetWidth - width;
        var adjust_height = obj.offsetHeight - height;
	
        window.resizeBy(adjust_width, adjust_height);
        obj.focus;
    }

    try { 
	    var e = document.getElementById('Q1_remaining_chars');
	    if (e ) e.style.display = 'block'; 
    }
    catch(e) { /* Error */ }
    

    try { 
      var form_page = document.getElementById('Q1');
      if ( !form_page )
      {
        var b = document.getElementById('footer_buttons');
        if ( b ) b.style.display = 'none'; 
        
        var t = document.getElementById('thanks');
        if ( t ) t.style.display = 'block'; 
        
        var t = document.getElementById('thank_you_form');
        if ( t ) t.style.display = 'block';   
      }
    }
    catch(e) { /* Error */ }
    
      
    //Code added by INDUSA to display this footer only when javascript in ENABLED
    
    var objfooter = GetElement('footer');
    if(objfooter)
    {
        objfooter.style.display = 'block';
    }
    
    var objfooter = GetElement('footer_default');
    if(objfooter)
    {
        objfooter.style.display = 'none';
    }
    
    //AES - add the onclick event for the essay question
    var quest = GetElement("Q1");
    if(quest){
	    try{
		    DebugMess("document.getElementById(Q1) is not null");

    	    quest.onkeyup = function () { update_chars_remaining(this); };
    	    quest.onkeypress = function () { return check_max_chars(this, event); };
    	    
		    DebugMess("hook in event handler is done ..");
	    }
	    catch(e) { 
	        DebugMess("hook in event handler FAILED .."); 
	        /* Error */ 
	    }
    }
    
    var node = document.getElementById("progress-bar1");
    if(node){ removeAllChildNodes(node); }
    
    DebugMess("Loading is complete");
    LoadJs();
}


function get_browser()
{
    browser = navigator.userAgent.toLowerCase();

    if (browser.indexOf('msie 6') != -1)
        browser = 'IE6';
    else if (browser.indexOf('msie 7') != -1)
        browser = 'IE7';
    else if (browser.indexOf('mozilla') != -1)
        browser = 'MOZILLA';
    else
        browser = 'UNKNOWN';
}

function update_chars_remaining(text_field)
{
    var id = text_field.id;
    var text = document.getElementById(id).value;
    var text_check = text.replace(/'|"|\n|\r|\\/g,'xx');
    var text_offset = text_check.length - text.length;

    var remaining_chars = _max_chars - text.length - text_offset;

    if (remaining_chars < 0)
    {
        document.getElementById(id).value = text.substring(0, (_max_chars - text_offset));
        remaining_chars = 0;
       
        AlertSpecial('maxlimit', maxLimitMessage);
    }
  
    id = id + '_remaining_chars';

    var charRemainingMessage = _charRemainingTex.replace("%REMAININGCHAR%", remaining_chars.toString());

    //document.getElementById(id).innerHTML = remaining_chars.toString() + " characters remaining.";
    document.getElementById(id).innerHTML = charRemainingMessage;
    
    if (text_field.value.trim().length > 0) {
        text_field.className = "HintActiveClass";
    }
}

function AlertSpecial(type, message)
{
    if(_lang == 'zh-CN')
    {
         var modalPage = modalLangPageBasePath + type + '-' + _lang + '.htm';
        window.open(modalPage, 'Warning', 'width=250, height=150, left='+(screen.availWidth/2 - 236)+', top='+(screen.availHeight/2 - 244)+', resizable, toolbar=0, location=0');
        /*
        if(window.showModalDialog) //If brower is IE
        {
         var modalPage = modalLangPageBasePath + type + '-' + _lang + '.htm';
         window.showModalDialog (modalPage,'','center:yes;dialogHeight:150px;dialogWidth:200px;status:no;help:no;scroll:no;');
        }
        else //browser is firefox
        {
            AlertMessage(maxLimitMessage);
        }  
        */
    }   
    else //when not Chinese
    {
        AlertMessage(message);
    }
}

//aes
function HandleHintClassDisplay(text_field)
{
    //AES - gray out comment hint text
    if(text_field.value == text_field.hintText || text_field.value == ""){
        text_field.className = HintClass;
    }
}

function check_max_chars(text_field, e)
{
    var keycode = (e.which)?e.which:e.keyCode;

    if (!((keycode == 8)||(keycode == 46)||((keycode >= 37)&&(keycode <= 40))))
    {
        //DON'T CHECK FOR MAX CHARS IF A BACKSPACE, DELETE OR ARROW KEY IS PRESSED

        var id = text_field.id;
        var text = document.getElementById(id).value;

        if (_max_chars <= text.length)
        {
            AlertMessage('Sorry, we ran out of space for your message.');
            return false;
        }
    }

    return true;
}

function clickclear(thisfield, defaulttext) {

  if (thisfield.value == defaulttext) {
    thisfield.value = "";
  }
}

function clickrecall(thisfield, defaulttext) {
  if (thisfield.value == "") {
    thisfield.value = defaulttext;
  }
}

function clickclearSTR(thisfield, tech, other) {
  if (thisfield.value == tech || thisfield.value == other) {
    thisfield.value = "";
    thisfield.style.color = "black";
  }
}

function clickrecallSTR(thisfield, tech, other) {
  targetform = document.getElementById('report_form');
  inputs = targetform.getElementsByTagName('input');
  if (thisfield.value == "" || thisfield.value == tech || thisfield.value == other) {
    for(i=0; i < inputs.length; i++) {
      if(inputs[i].name == 'feedback_type' && inputs[i].checked == true) {
        switchSTRtext(inputs[i],tech,other);
        thisfield.style.color = "gray";
      }
    }
  } else {
    for(i=0; i < inputs.length; i++) {
      if(inputs[i].name == 'feedback_type' && inputs[i].checked == true) {
        switchSTRtext(inputs[i],tech,other);
   	    thisfield.style.color = "black";
	    //update_chars_remaining(thisfield, 4000);
	    update_chars_remaining(thisfield);
	  	clearError(thisfield,tech,other);
      }
    }
  }
}

function switchSTRtext(e,tech,other) {
  target = document.getElementById('Q1');
  target_label = document.getElementById('label_Q1');
  if(e.value == "Other") {
  	if(target.value == tech || target.value == other || target.value == "") {
  	  target.value = other;
      target_label.innerHTML = other_label;
      target_label.title = other_title;
  	} else {
      target_label.innerHTML = other_label;
      target_label.title = other_title;
  	}
  } else if(e.value == "Technical")  {
  	if(target.value == other || target.value == tech || target.value == "") {
  	  target.value = tech;
      target_label.innerHTML = tech_label;
      target_label.title = tech_title;
  	} else {
      target_label.innerHTML = tech_label;
      target_label.title = tech_title;
  	}
  } else {

    target_label.innerHTML = tech_label;
    target_label.title = tech_title;
	clearError(target,tech,other);
  }
}

function clearError(e,tech,other) {
  if(e.value != "" || e.value != other || e.value != tech ) {
    target = "error_"+e.id;
    target = document.getElementById(target);
    tStyle = target.style.display = 'none';
	e.style.color="black";
  }
}

function checkFeedbackOnload() {
  e = document.getElementById('Q1');
  clickrecallSTR(e,tech,other);
}

function addLoadEvent(func){
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function(){
			oldonload();
			func();
		}
	}
}

function removeAllChildNodes(node) {
	if (node && node.hasChildNodes && node.removeChild) {
		while (node.hasChildNodes()) {
			node.removeChild(node.firstChild);
		}
	}
}

function createjscssfile(filename, filetype){

 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 return fileref
}

function replacejscssfile(oldfilename, newfilename, filetype){
 var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist using
 var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
 var allsuspects=document.getElementsByTagName(targetelement)
 for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
  if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(oldfilename)!=-1){
   var newelement=createjscssfile(newfilename, filetype)
   allsuspects[i].parentNode.replaceChild(newelement, allsuspects[i])
  }
 }
}

function getUrlParameter( name, defaultValue )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return defaultValue;
  else
    return results[1];
}

// define a custom method on the string class to trim leading and training spaces
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };

function initHintTextboxes() {
  if(!commentHint){ commentHint = ""; }
  if(!emailHint){ emailHint = ""; }

  initHint(document.getElementById("Q1"), commentHint);
  initHint(document.getElementById("Q3_1"), emailHint);
}

function initHint(input,hint)
{

  if ( input )
  {
	input.value = hint;
	input.hintText = input.value;
	input.className = "HintClass";
	input.onfocus = onHintTextboxFocus;
    input.onblur = onHintTextboxBlur;
  }
}

function onHintTextboxFocus() {
   //DebugMess("onHintTextboxFocus() is called");
   var input = this;
 
  var str = input.value.trim();
  
  if (str == input.hintText) {
    input.value = "";
    input.className = "HintActiveClass";
    if (input.id == "Q1")
    {
	    update_chars_remaining(input, _max_chars);
        update_chars_remaining(input);        
    }
  }
  else{ 
    input.className = "HintActiveClass";
  }
}

function onHintTextboxBlur() {
    var input = this;
    if (input.value.trim().length==0) {
        input.value = input.hintText;
        input.className = "HintClass";
    }
}

function Validate(){
  
    var text_field = document.getElementById("Q1");
    var text = text_field.value;
    var text_check = text.replace(/'|"|\n|\r|\\/g,'xx');
    var text_offset = text_check.length - text.length;
    text_field.hintText
    var remaining_chars = _max_chars - text.length - text_offset;
  
   if((text.toString() == text_field.hintText.toString()) ||( remaining_chars < 0 ) || ( remaining_chars > (_max_chars - 3))){
        AlertSpecial('comment', commentValidation);
	    return false;
    }
    else if(!IsValidEmail("Q3_1")){
        AlertSpecial('email', emailValidation);
    	return false;
    }
    else{
        ClearEmailResponse();
       	PageNext();
       	return true;
    }
}

function ClearEmailResponse(){

    var input = GetElement("Q3_1");
    if(!input){ return; }
  
    var str = input.value.trim();
    //clear out the response to prevent submitting the hint text
    if (str == input.hintText) {
        input.value = "";
    }
}


function CloseForm(){
	//window.close();
	/*
	var buttonPressed = GetElement("PdcButtonPressed");
	
	if(form && document.PdcSurvey){
	    buttonPressed.value = 'submit';
	    PageNext();
	}
	*/
}

function LoadJs(){
 DebugMess("In LoadJs");
     try { 
    	LoadJsFile();
     }
     catch(e) { /* Error */ }
}


function PageNext(){
    try{
        if (document.PdcSurvey.next) {
		    document.PdcSurvey.next.click();
	    } else if (document.PdcSurvey.submit) {
		    document.PdcSurvey.submit.click();
	    } else {
		    document.PdcSurvey.submit();
	    }
	   return;
	}
	catch(e) { 
	    /* Error */ 
	    DebugMess(e);
	}
	
	 try{
	    var submit = GetElement('submit_button_default');
	    if(submit){ submit.click(); }
	 }
	 catch(e) { 
	    /* Error */ 
	    DebugMess(e);
	}
}

/// <summary>
/// Indicates if the specified fill in topic contains a valid e-mail address.
/// </summary>
/// <param name="heading">A valid dbHeading</param>
function IsValidEmail(heading) {
	var inputField = document.getElementById(heading);
	if (inputField) {
		var email = inputField.value;
		if ( email == inputField.hintText ) { return true; }
		if(email.trim().length==0){ return true; }
		if (email.match(/^[\w_\-\.]+[\%\+]?[\w_\-\.]*\@[0-9a-zA-Z\-]+\.[0-9a-zA-Z\-\.]+$/)) return true;
	}
	return false;
}


var windowOptions = 'toolbar=yes,location=yes,directories=yes,resizable=yes,scrollbars=yes';

function OpenUrl(url)
{
    window.open(url, '_blank', windowOptions);
}

//<script type="text/javascript" src="http://o.aolcdn.com/omniunih.js"></script>

/*

The code that opens the initial feedback form is responsible for scraping the referring page's Omniture channel value and passing that along in the URL.  The value can then be scraped and placed into the s_265.prop16 variable.  The page's channel value will be in one of two variables:  s_channel or s_265.channel. This will be passed to Clarabridge using the ch URL parameter (e.g. &ch=us.beta)

The feedback form is responsible for creating a unique Feedback ID. The feedback ID should be placed into the s_265.prop17 variable. 

The s_265.prop16 and s_265.prop17 values should be passed from the feedback form to the confirmation page, so they can be re-populated there.

The s_265.prop18 will need to be set with the oid value passed in the URL (e.g., &oid=0887127da8f0b062e18d940c9d763ba6)

Please make sure to use the appropriate s_account value in development and testing, and only switch to the production value when the forms are being launched to production.  I will need a page view estimate, including both forms, for the first 30 days post launch with tracking.  I need this total 5 business days in advance of launch.
*/

//sample link
//http://www.unitedtracksurvey.com/se.ashx?s=04BD76CC65A7BB3C&c=en-US&tid=2&preview=1&ch=chvalue&oid=oidval

//This function is responsible for generating a unique feedback id

/*
function GenerateFeedbackCode(){
        var uniqueId= guid();
        return uniqueId;
}

//This function will create a random unique guid kind of id 
function guid() {
   return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}


//This function is used to return random numbers
function S4() {
   return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
*/

//Clarabridge- AOL Voice of the Consumer Feedback Collection
//Here is the Omniture code for the "Standard" feedback collection form:
function GetFeedbackFormOmnitureCode(ch, fid, oid)
{

	try { 
	    //move this declaration to the questionnaire project
		//var s_account="aolvotcdev";  /* use 'aolvotc' when changing to production environment */

		s_265.linkInternalFilters="javascript:,aol.com";
		s_265.pfxID="voc";
		s_265.channel="us.votc";
		s_265.pageName=s_265.pfxID + " : " + "Feedback Form";
		s_265.prop1=s_265.pfxID + " : Standard Form";
		s_265.prop2=s_265.pfxID;
		s_265.prop12=document.URL;

		//Vovici is responsible for setting prop16,prop17,prop18
		s_265.prop16=ch //[grab ch (channel) value from URL];
		s_265.eVar1=s_265.prop16; 
		s_265.prop17=fid; //[auto-generate feedback ID];
		s_265.prop18=oid; //[grab oid value from URL];

		s_265.events="prodview,event1";
		s_265.products=";Standard Feedback Form";
		var s_code=s_265.t();
	}
	catch(e) { /* Error */ }
}


//Here is the Omniture code for the "Standard" feedback 'thank you' page after successful submission:


function GetThankYouPageOmnitureCode()
{
	try { 
		//Vovici is responsible for setting prop16,prop17,prop18
		GetPipedValues();

        //move this declaration to the questionnaire project
		//var s_account="aolvotcdev";  /* use 'aolvotc' when changing to production environment */

		s_265.linkInternalFilters="javascript:,aol.com";
		s_265.pfxID="voc";
		s_265.channel="us.votc";
		s_265.pageName=s_265.pfxID + " : " + "Feedback Submitted - Confirmation";
		s_265.prop1=s_265.pfxID + " : Standard Form";
		s_265.prop2=s_265.pfxID;
		s_265.prop12=document.URL;

		//Vovici is responsible for setting prop16,prop17,prop18
		s_265.prop16=_ch; //[grab ch (channel) value from URL];
		s_265.eVar1=s_265.prop16;
		s_265.prop17=_fid; //get the feedback id from the url
		s_265.prop18=_oid; //[grab oid value from URL];

		s_265.events="purchase,event2";
		s_265.products=";Standard Feedback Form;1;0";
		var s_code=s_265.t();
	}
	catch(e) { /* Error */ }

}

function GetPipedValues()
{
        //The following url fields captured on the server side using the custom survey event handler and is then piped into html variabvle as a placeholder value
      
        //get the feedback id as the record for this participant
        if(typeof _feedbackId != "undefined"){
            _fid = _feedbackId;
        }
        //get the chanel url value
        if(typeof _chanelUrlVal != "undefined"){
            _ch = _chanelUrlVal;
        }
        //get the feedback id ur value
        if(typeof _oidUrlVal != "undefined"){
            _oid = _oidUrlVal; 
        }
        //get the feedback id ur value
        if(typeof _languageId != "undefined"){
            _lang = _languageId; 
        }
        
}

function GetElement(elementName) {
    var reference = null;
    
    if (document.getElementById) {
        reference = document.getElementById(elementName);
    }
    if (reference == null && document.all) {
        reference = document.all[elementName];
    }
    if (reference == null && document.PdcSurvey) {
        reference = document.PdcSurvey[elementName];
    }
    
    return reference;
}

function GetElementValue(elementName, defautValue) {
    var reference = GetElement(elementName);
   
    if (reference) {
        return reference.value;
    }else{
        return defautValue;
    }
}

function SetElementValue(elementName, val) {
    var reference = GetElement(elementName);
   
    if (reference) {
        reference.value = val;
    }
}

function URLDecode (encodedString) {
  var output = encodedString;
  var binVal, thisString;
  var myregexp = /(%[^%]{2})/;
  while ((match = myregexp.exec(output)) != null
             && match.length > 1
             && match[1] != '') {
    binVal = parseInt(match[1].substr(1),16);
    thisString = String.fromCharCode(binVal);
    output = output.replace(match[1], thisString);
  }
  return output;
}

function validateOnEnterKey(evt)
 { 
    
  var evt = (evt) ? evt : ((event) ? event : null); 
  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null); 
  if ((evt.keyCode == 13) ) 
   {
    
    if(node.id=="Q1")
    {
        
        return evt.keyCode;
    }
    else
    {
        if (Validate())
	{
            return evt.keyCode;
        }
        else
        {
	    return false;
        }
    }  
  } 
}

// used in submit_form function to prevent multi-submit via rapid multi-clicks
function submit_form ( )
{
  if ( form_submitted )
  {
    alert ( "Thank you for your response." );
    return false;
  }
  else
  {
    form_submitted = PdcProcessPage();
    return form_submitted;
  }
}

window.onload = page_init;
