﻿var opera = (navigator.appName.indexOf("Opera") != -1) ? true : false;
var firefox = navigator.userAgent.toLowerCase();
    firefox = (firefox.indexOf("firefox") != -1) ? true : false;
var safari = navigator.userAgent.toLowerCase();
    safari = ((safari.indexOf("safari") != -1) && (safari.indexOf("chrome") == -1)) ? true : false;
var chrome = navigator.userAgent.toLowerCase();
    chrome = (chrome.indexOf('chrome') != -1) ? true : false;
var msie_only = (navigator.appName.indexOf("Microsoft") != -1) ? true : false;
var msie_old = false; // MSIE versions older than 7
var msie_80 = false; // MSIE version 8.0 or newer
var msie_70 = false; // MSIE version 7.0
var msie_60 = false; // only MSIE 6.0
var msie_55 = false; // only MSIE 5.5

if (msie_only) {
  fullVerStr = navigator.appVersion;
  verStr = fullVerStr.substring(fullVerStr.indexOf('MSIE') + 4, fullVerStr.length);
  verStr = verStr.substring(0, verStr.indexOf(';'));
  msie_old = (parseFloat(verStr) < 7.0) ? true : false;
  msie_80 = (parseFloat(verStr) >= 8.0) ? true : false;
  msie_70 = (parseFloat(verStr) == 7.0) ? true : false;
  msie_60 = (parseFloat(verStr) == 6.0) ? true : false;
  msie_55 = (parseFloat(verStr) == 5.5) ? true : false;
}

document.writeln('<style type="text/css">\n/*<![CDATA[*/\n');
if (msie_80) {
  document.writeln('.Radio,  .CheckBox  {margin-left:4px; margin-right:2px; top:3px;}\n');
  document.writeln('.Radio2, .CheckBox2 {margin-right:2px; top:3px;}\n');
  document.writeln('.RbVerticalList {left:-6px; top:-2px;}\n');
  document.writeln('.RbVerticalList input {position:relative; top:3px;  margin-top:4px; margin-bottom:4px; margin-right:3px;}\n');
  document.writeln('.CbVerticalList {left:-6px; top:-2px;}\n');
  document.writeln('.CbVerticalList input {position:relative; top:3px; margin-top:4px; margin-bottom:4px; margin-right:3px;}\n');
}
if (msie_70) {
  document.writeln('.RbVerticalList {left:-6px; top:-2px;}\n');
  document.writeln('.RbVerticalList input {position:relative; top:3px; left:-5px;}\n');
  document.writeln('.CbVerticalList {left:-6px; top:-2px;}\n');
  document.writeln('.CbVerticalList input {position:relative; top:3px; left:-5px;}\n');
  document.writeln('ol {margin-left:36px;}\n');
}
if (msie_old) {
  document.writeln('.MainDiv .MainContent .MainLeft {height:200px;}\n');
  document.writeln('.FBLongVersion {width:668px;}\n');
  document.writeln('.Radio,  .CheckBox  {top:2px;}\n');
  document.writeln('.Radio2, .CheckBox2 {top:2px;}\n');
  document.writeln('.MainDiv .MainHeader {height:126px;}\n');
  document.writeln('.MainDiv .MainContent {height:300px;}\n');
  document.writeln('.MainDiv .MainContent .MainLeft {height:200px;}\n');
  document.writeln('.RbHorizontalList input {left:-7px;}\n');
  document.writeln('.RbHorizontalList label {left:-7px;}\n');
  document.writeln('.RbVerticalList {left:-6px; top:-2px;}\n');
  document.writeln('.RbVerticalList input {position:relative; top:2px; left:-5px;}\n');
  document.writeln('.CbVerticalList {left:-6px; top:-2px;}\n');
  document.writeln('.CbVerticalList input {position:relative; top:2px; left:-5px;}\n');
  document.writeln('.AnswersBlock table td input {margin-bottom:3px;}\n');
  document.writeln('.AccessCBList input {margin-right:0px;}\n');
  document.writeln('.AccessCBList label {margin-right:7px;}\n');
  document.writeln('.LocalNav {top:0px;}\n');
}
if (msie_only) {
}
if (opera) {
  document.writeln('.Radio,  .CheckBox  {margin-left:4px;  margin-right:0px; top:1px}\n');
  document.writeln('.Radio2, .CheckBox2 {margin-left:15px; margin-right:0px; top:1px}\n');
  document.writeln('.RbHorizontalList input {}\n');
  document.writeln('.RbHorizontalList label {top:0px;}\n');
  document.writeln('.RbVerticalList {left:-1px;}\n');
  document.writeln('.RbVerticalList input {margin-top:3px; margin-bottom:3px;}\n');
  document.writeln('.CbVerticalList {left:-1px;}\n');
  document.writeln('.CbVerticalList input {margin-top:3px; margin-bottom:3px;}\n');
  document.writeln('.RadioButtonWLabel .Radio {padding-top:4px;}\n');
  document.writeln('.AccessCBList label {top:1px;}\n');
}
if (firefox) {
  document.writeln('.Radio,  .CheckBox  {margin:4px 3px 4px 4px;  top:2px;}\n');
  document.writeln('.Radio2, .CheckBox2 {margin:4px 3px 4px 15px; top:2px;}\n');
  document.writeln('.RbHorizontalList label {top:-3px;}\n');
  document.writeln('.RbVerticalList input {margin-top:4px; margin-bottom:3px;}\n');
  document.writeln('.RbVerticalList label {position:relative; top:-3px; margin-left:6px;}\n');
  document.writeln('.CbVerticalList input {margin-top:4px; margin-bottom:3px;}\n');
  document.writeln('.CbVerticalList label {position:relative; top:-3px; margin-left:6px;}\n');
}
if (safari) {
  document.writeln('.Radio,  .CheckBox  {margin:4px 4px 4px 4px; top:2px;}\n');
  document.writeln('.Radio2, .CheckBox2 {margin:4px 4px 4px 15px; top:2px;}\n');
  document.writeln('.RbVerticalList input {position:relative; margin-top:4px; margin-bottom:3px; top:3px;}\n');
  document.writeln('.RbVerticalList label {top:-3px; margin-left:7px;}\n');
  document.writeln('.CbVerticalList input {position:relative; margin-top:4px; margin-bottom:3px; top:2px;}\n');
  document.writeln('.CbVerticalList label {margin-left:7px;}\n');
  document.writeln('.QualiTable .Col3 select {line-height:1.5em;}\n');
  document.writeln('.QualiTable .Col4 select {line-height:1.5em;}\n');
  document.writeln('ol {margin-left:32px;}\n');
}
if (chrome) {
  document.writeln('.Radio,  .CheckBox  {margin:4px 2px 4px 4px; top:3px;}\n');
  document.writeln('.Radio2, .CheckBox2 {margin:4px 2px 4px 15px; top:3px;}\n');
  document.writeln('.RbVerticalList input {position:relative; margin-top:4px; margin-bottom:4px; top:3px;}\n');
  document.writeln('.RbVerticalList label {top:-3px; margin-left:7px;}\n');
  document.writeln('.CbVerticalList input {margin-top:4px; margin-bottom:4px;}\n');
  document.writeln('.CbVerticalList label {position:relative; top:-2px; margin-left:7px;}\n');
  document.writeln('ol {margin-left:32px;}\n');
}
if (!msie_70 && !msie_old) {
  document.writeln('.MainDiv .MainBGTop {z-index:0 !important}\n');
  document.writeln('.MainDiv .MainContent {position:relative}\n');
}
document.writeln('/*]]>*/\n</style>\n');

// Default english texts. For admin zone and when not set on public master page.
var MaximumTextLengthIsXXWords = "Maximum text length is [XX] words.";
var MaximumTextLengthIsXXCharacters = "Maximum text length is [XX] characters.";
var YouMayEnterXXMoreCharacters = "You may enter [XX] more characters.";
var YouMayEnterXXMoreWords = "You may enter [XX] more words.";

//top image list
image_array = new Array();
image_array[0] = '<img src="/images/default/top2_1.jpg" alt="" />';
image_array[1] = '<img src="/images/default/top2_2.jpg" alt="" />';
image_array[2] = '<img src="/images/default/top2_3.jpg" alt="" />';
image_array[3] = '<img src="/images/default/top5_1.jpg" alt="" />';
image_array[4] = '<img src="/images/default/top6_1.jpg" alt="" />';
image_array[5] = '<img src="/images/default/top6_2.jpg" alt="" />';
image_array[6] = '<img src="/images/default/top6_3.jpg" alt="" />';
image_array[7] = '<img src="/images/default/top7_1.jpg" alt="" />';
image_array[8] = '<img src="/images/default/top9_01.jpg" alt="" />';
image_array[9] = '<img src="/images/default/top9_02.jpg" alt="" />';
image_array[10] = '<img src="/images/default/top9_03.jpg" alt="" />';
image_array[11] = '<img src="/images/default/top9_04.jpg" alt="" />';
image_array[12] = '<img src="/images/default/top9_06.jpg" alt="" />';
image_array[13] = '<img src="/images/default/top9_07.jpg" alt="" />';
image_array[14] = '<img src="/images/default/top9_08.jpg" alt="" />';
image_array[15] = '<img src="/images/default/top9_09.jpg" alt="" />';
image_array[16] = '<img src="/images/default/top9_10.jpg" alt="" />';
image_array[17] = '<img src="/images/default/top9_11.jpg" alt="" />';
image_array[18] = '<img src="/images/default/top9_12.jpg" alt="" />';
image_array[19] = '<img src="/images/default/top9_13.jpg" alt="" />';
image_array[20] = '<img src="/images/default/top9_14.jpg" alt="" />';
image_array[21] = '<img src="/images/default/top9_15.jpg" alt="" />';
image_array[22] = '<img src="/images/default/top9_16.jpg" alt="" />';
image_array[23] = '<img src="/images/default/top9_17.jpg" alt="" />';
image_array[24] = '<img src="/images/default/top9_18.jpg" alt="" />';
image_array[25] = '<img src="/images/default/top9_19.jpg" alt="" />';

function shuffle(array) {
  var tmp, current, top = array.length;
  if (top) while (--top) {
    current = Math.floor(Math.random() * (top + 1));
    tmp = array[current]; array[current] = array[top];
    array[top] = tmp;
  } 
  return array;
}

shuffled_array = shuffle(image_array);

function imagePicker() {
  for (var i = 0; i <= 7; i++) {
    document.write(shuffled_array[i])
  }
  $('.HeaderThumbs img:last').addClass('LastThumb')
}

//Limits length of text in textarea "element" (dom reference), writes information in "info" (id), counts characters
function checkLength(element, info, max_length) {
  var actual_length = element.value.length;
  var characters_left = max_length - actual_length;
  if (characters_left < 0) characters_left = 0;

  if (actual_length == 0) {
    document.getElementById(info).innerHTML = MaximumTextLengthIsXXCharacters.replace("[XX]", max_length);
  }
  if ((actual_length > 0) && (actual_length <= max_length)) {
    document.getElementById(info).innerHTML = YouMayEnterXXMoreCharacters.replace("[XX]", characters_left);
  }
  if (actual_length > max_length) {
    element.value = element.value.substr(0, max_length);
    document.getElementById(info).innerHTML = YouMayEnterXXMoreCharacters.replace("[XX]", characters_left);
  }
}

//init a textarea, textarea_container - id, for charaacters limit
function initLengthInfo(textarea_container, info_id, max_length) {
  if (document.getElementById(textarea_container)) {
    element_ref = document.getElementById(textarea_container).getElementsByTagName("textarea")[0];
    checkLength(element_ref, info_id, max_length);
  }
}

//trims only spaces from the end of a string
function trim(text) {
  while (text.charAt(text.length - 1) == " ") {
    text = text.substr(0, (text.length - 1));
  }
  return (text);
}

//Limits length of text in textarea "element" (dom reference), writes information in "info" (id), counts words
function checkLengthWords(element, info, max_length) {
  var text_trimmed = trim(element.value);
  var text_in_array = new Array();
  if (text_trimmed.length > 0)
    text_in_array = text_trimmed.split(" ");
  var actual_length = text_in_array.length;
  var words_left = max_length - actual_length;
  if (words_left < 0) words_left = 0;

  if (actual_length == 0) {
    document.getElementById(info).innerHTML = MaximumTextLengthIsXXWords.replace("[XX]", max_length);
  }
  if ((actual_length > 0) && (actual_length <= max_length)) {
    document.getElementById(info).innerHTML = YouMayEnterXXMoreWords.replace("[XX]", words_left);
  }
  if (actual_length > max_length) {
    text_in_array = text_in_array.slice(0, max_length);
    element.value = text_in_array.join(" ") + " ";
    document.getElementById(info).innerHTML = YouMayEnterXXMoreWords.replace("[XX]", words_left);
  }
}

//init a textarea, textarea_container - id, for words limit
function initLengthInfoWords(textarea_container, info_id, max_length) {
  if (document.getElementById(textarea_container)) {
    var element_ref = document.getElementById(textarea_container).getElementsByTagName("textarea")[0];
    checkLengthWords(element_ref, info_id, max_length);
  }
}

/* Displays time left, takes value from hidden field and updates it, page refresh issue taken care of (cookie), clicks next button on time out */
/* cookie_id - any unique string for the test to avoid conflicts between tests */
/* TL - time left, ST test was started within 30 minutes - to stop timer from reseting (when reset_cookie=true) within 30 min from the start. It would happen if page was refreshed */
var end_time_in_ms = "-1";
var timer_id;
function countDown(hidden_field_container_id, visual_element_id, button_to_click, cookie_id, reset_cookie) {
  if (reset_cookie.toLowerCase() == "true") {
    if (fromCookie(cookie_id + "ST") != "1") {
      toCookie2(cookie_id + "TL", "-1", "-1"); //reset the timer
      toCookie2(cookie_id + "ST", "1", "1800") //1800 = 30min
    }
  }

  var time_left_calculated_sec_all = 0;
  var time_left_calculated_min = 0;
  var time_left_calculated_sec = 0;
  var time_left_calculated_sec_zero_corrected = "";
  var sec_from_hidden = parseInt(document.getElementById(hidden_field_container_id).getElementsByTagName("input")[0].value);
  var sec_from_cookie = parseInt(fromCookie(cookie_id + "TL"));
  var sec_to_use = 0;
  var dateObj = new Date();
  
  if (sec_from_hidden <= 0) sec_from_hidden = 0;
  
  if (sec_from_cookie > -1) {
    sec_to_use = (sec_from_cookie < sec_from_hidden) ? sec_from_cookie : sec_from_hidden;
  } else {
    sec_to_use = sec_from_hidden;
  }

  var current_time_in_ms = dateObj.getTime();

  if (end_time_in_ms == -1) {
    end_time_in_ms = dateObj.getTime() + sec_to_use * 1000;
  }

  time_left_calculated_sec_all = Math.floor((end_time_in_ms - current_time_in_ms)/1000);
  if (time_left_calculated_sec_all < 0)
    time_left_calculated_sec_all = 0;
  time_left_calculated_min = Math.floor(time_left_calculated_sec_all / 60);
  time_left_calculated_sec = time_left_calculated_sec_all % 60;
  time_left_calculated_sec_zero_corrected = String(time_left_calculated_sec);
  if (time_left_calculated_sec <= 9)
    time_left_calculated_sec_zero_corrected = "0" + time_left_calculated_sec_zero_corrected;
  document.getElementById(visual_element_id).innerHTML = "<span class=\"Minute\">" + String(time_left_calculated_min) + "</span>:<span class=\"Second\">" + time_left_calculated_sec_zero_corrected + "</span>";
  document.getElementById(hidden_field_container_id).getElementsByTagName("input")[0].value = time_left_calculated_sec_all;
  
  toCookie(cookie_id + "TL", String(time_left_calculated_sec_all)); // 1 year valid cookie
  
  if (time_left_calculated_sec_all > 0) {
    timer_id = setTimeout("countDown('" + hidden_field_container_id + "', '" + visual_element_id + "', '" + button_to_click + "', '" + cookie_id + "', 'false')", 500);
  } else {
    toCookie2(cookie_id + "TL", "-1", "-1");
    var button_to_click_ref = document.getElementById(button_to_click).getElementsByTagName("a")[0];
    var button_to_click_href_function = button_to_click_ref.href.substring(11, button_to_click_ref.href.length);
    eval(button_to_click_href_function);
  }
}

/* Stop the timer when the next button is clicked and page is waiting to be reloaded */
function StopTimer() {
  window.clearTimeout(timer_id);
}

//STATUS OF COMPLETED MODULES / PROGRESS INDICATION
function toCookie(cookie_id, value) {
  var exp = new Date();
  exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 365));
  var cookie_name = "Coast_" + cookie_id + "=" + value;
  var cookie_expires = "expires=" + exp.toGMTString();
  document.cookie = cookie_name + ";" + cookie_expires + "; path=/";
}

function toCookie2(cookie_id, value, exp_sec) { //function with cookie expire time parameter added
  var exp = new Date();
  exp.setTime(exp.getTime() + (exp_sec * 1000)); // time is in ms
  var cookie_name = "Coast_" + cookie_id + "=" + value;
  var cookie_expires = "expires=" + exp.toGMTString();
  document.cookie = cookie_name + ";" + cookie_expires + "; path=/";
}

//Returns value stored in cookie with given id, or -1 if cookie didn't exist (or is expired), multi value cookies resistant.
//issue noticed: "abc" is conflicting with "abcd", any one cookie_id cannot be a part of other cookie_id
function fromCookie(cookie_id) {
  var labelName = "Coast_" + cookie_id;
  var labelLen = labelName.length;
  var cookieData = document.cookie;
  var cLen = cookieData.length;
  var i = 0;
  var cEnd;
  while (i < cLen) {
    var j = i + labelLen;
    if (cookieData.substring(i, j) == labelName) {
      cEnd = cookieData.indexOf(";", j);
      if (cEnd == -1) {
        cEnd = cookieData.length;
      }
      return unescape(cookieData.substring(j + 1, cEnd));
    }
    i++;
  }
  return "-1";
}

//High contrast picker
function switchToHighContrast() {

  if ((fromCookie("HighContrast") == "0") || (fromCookie("HighContrast") == "2") || (fromCookie("HighContrast") == "3") || (fromCookie("HighContrast") == "-1")) {
    if (document.getElementsByTagName("link")[3]) document.getElementsByTagName("link")[3].disabled = true;
    if (document.getElementsByTagName("link")[2]) document.getElementsByTagName("link")[2].disabled = true;
    if (document.getElementsByTagName("link")[1]) document.getElementsByTagName("link")[1].disabled = true;
    if (document.getElementsByTagName("link")[1]) document.getElementsByTagName("link")[1].disabled = false;
    toCookie("HighContrast", "1");

  }
}

function switchToHighContrast2() {
  if ((fromCookie("HighContrast") == "0") || (fromCookie("HighContrast") == "1") || (fromCookie("HighContrast") == "3") || (fromCookie("HighContrast") == "-1")) {
    if (document.getElementsByTagName("link")[1]) document.getElementsByTagName("link")[1].disabled = true;
    if (document.getElementsByTagName("link")[3]) document.getElementsByTagName("link")[3].disabled = true;
    if (document.getElementsByTagName("link")[2]) document.getElementsByTagName("link")[2].disabled = true;
    if (document.getElementsByTagName("link")[2]) document.getElementsByTagName("link")[2].disabled = false;
    toCookie("HighContrast", "2");
  }
}

function switchToHighContrast3() {
  if ((fromCookie("HighContrast") == "0") || (fromCookie("HighContrast") == "2") || (fromCookie("HighContrast") == "1") || (fromCookie("HighContrast") == "-1")) {
    if (document.getElementsByTagName("link")[1]) document.getElementsByTagName("link")[1].disabled = true;
    if (document.getElementsByTagName("link")[2]) document.getElementsByTagName("link")[2].disabled = true;
    if (document.getElementsByTagName("link")[3]) document.getElementsByTagName("link")[3].disabled = true;
    if (document.getElementsByTagName("link")[3]) document.getElementsByTagName("link")[3].disabled = false;
    toCookie("HighContrast", "3");
  }
}

function switchToDefault() {
  if ((fromCookie("HighContrast") == "1") || (fromCookie("HighContrast") == "2") || (fromCookie("HighContrast") == "3") || (fromCookie("HighContrast") == "-1")) {
    if (document.getElementsByTagName("link")[3]) document.getElementsByTagName("link")[3].disabled = true;
    if (document.getElementsByTagName("link")[2]) document.getElementsByTagName("link")[2].disabled = true;
    if (document.getElementsByTagName("link")[1]) document.getElementsByTagName("link")[1].disabled = true;
    toCookie("HighContrast", "0");
  }
}

function initContrastCSS() {
  if (fromCookie("HighContrast") == "1") {
    if (document.getElementsByTagName("link")[3]) document.getElementsByTagName("link")[3].disabled = true;
    if (document.getElementsByTagName("link")[2]) document.getElementsByTagName("link")[2].disabled = true;
    if (document.getElementsByTagName("link")[1]) document.getElementsByTagName("link")[1].disabled = true;
    if (document.getElementsByTagName("link")[1]) document.getElementsByTagName("link")[1].disabled = false;
  }
  else if (fromCookie("HighContrast") == "2") {
    if (document.getElementsByTagName("link")[3]) document.getElementsByTagName("link")[3].disabled = true;
    if (document.getElementsByTagName("link")[1]) document.getElementsByTagName("link")[1].disabled = true;
    if (document.getElementsByTagName("link")[2]) document.getElementsByTagName("link")[2].disabled = true;
    if (document.getElementsByTagName("link")[2]) document.getElementsByTagName("link")[2].disabled = false;
  }
  else if (fromCookie("HighContrast") == "3") {
    if (document.getElementsByTagName("link")[1]) document.getElementsByTagName("link")[1].disabled = true;
    if (document.getElementsByTagName("link")[2]) document.getElementsByTagName("link")[2].disabled = true;
    if (document.getElementsByTagName("link")[3]) document.getElementsByTagName("link")[3].disabled = true;
    if (document.getElementsByTagName("link")[3]) document.getElementsByTagName("link")[3].disabled = false;
  }
  else {
    if (document.getElementsByTagName("link")[1]) document.getElementsByTagName("link")[1].disabled = true;
    if (document.getElementsByTagName("link")[2]) document.getElementsByTagName("link")[2].disabled = true;
    if (document.getElementsByTagName("link")[3]) document.getElementsByTagName("link")[3].disabled = true;
  }
}

//Text size picker
function textSize1() {
  $("body").css("fontSize", "62.5%");
  $('.NormalState').css({ display: 'block', position: 'relative', top: '0px', right: '0px', height: '110px' })
  $('.FormOpen').css('display', 'none')
  $('.CallBackRequest a').css({ paddingTop: '3px', paddingBottom: '2px' })
  $('.CallBackRequest input').css('width', '97px')
  $('.ButtonStd .Centre a').css("padding-top","7px");
  $('.ButtonStd .Centre a').css("padding-bottom","9px");
  $('.ButtonStd2 .Centre a').css("padding-top","7px");
  $('.ButtonStd2 .Centre a').css("padding-bottom","9px");
  $('.ButtonStdSmall .Centre').css("height", "19px"); 
  toCookie("TextSize", "1");
}

function textSize2() {
  $("body").css("fontSize", "82.5%");
  $('.NormalState').css({ display: 'none', position: 'absolute', top: '0px', right: '0px', height: '220px', width: '240px' })
  $('.FormOpen').css('display', 'block')
  $('.CallBackRequest a').css({ paddingTop: '0px', paddingBottom: '4px' })
  $('.SendButton').css('marginRight', '10px')
  $('.CallBackRequest input').css('width', '9.7em')
  $('.ButtonStd .Centre a').css("padding-top","4px");
  $('.ButtonStd .Centre a').css("padding-bottom","5px");
  $('.ButtonStd2 .Centre a').css("padding-top","4px");
  $('.ButtonStd2 .Centre a').css("padding-bottom","5px");
  $('.ButtonStdSmall .Centre').css("height", "24px"); 
  toCookie("TextSize", "2");
}

function textSize3() {
  $("body").css("fontSize", "100%");
  $('.NormalState').css({ display: 'none', position: 'absolute', top: '0px', right: '0px', height: '220px', width: '240px' })
  $('.FormOpen').css('display', 'block')
  $('.CallBackRequest a').css({ paddingTop: '0px', paddingBottom: '4px' })
  $('.SendButton').css('marginRight', '10px')
  $('.CallBackRequest input').css('width', '9.7em')
  $('.ButtonStd .Centre a').css("padding-top","0px");
  $('.ButtonStd .Centre a').css("padding-bottom","2px");
  $('.ButtonStd2 .Centre a').css("padding-top","0px");
  $('.ButtonStd2 .Centre a').css("padding-bottom","2px");
  $('.ButtonStdSmall .Centre').css("height", "29px"); 
  toCookie("TextSize", "3");
}

function initcheckTextSize() {
  document.writeln('<style type="text/css">\n/*<![CDATA[*/\n');

  if (fromCookie("TextSize") == "3") {
    document.writeln('body {font-size:100%;}\n');
    document.writeln('.ButtonStd .Centre a  {padding-top:0px; padding-bottom:2px;}\n');
    document.writeln('.ButtonStd2 .Centre a {padding-top:0px; padding-bottom:2px;}\n');
    document.writeln('.ButtonStdSmall .Centre {height:29px;}\n'); 
  }
  else if (fromCookie("TextSize") == "2") {
    document.writeln('body {font-size:82.5%;}\n');
    document.writeln('.ButtonStd .Centre a  {padding-top:4px; padding-bottom:5px;}\n');
    document.writeln('.ButtonStd2 .Centre a {padding-top:4px; padding-bottom:5px;}\n');
    document.writeln('.ButtonStdSmall .Centre {height:24px;}\n'); 
  }
  else {
    document.writeln('body {font-size:62.5%;}\n');
    document.writeln('.ButtonStd .Centre a  {padding-top:7px; padding-bottom:9px;}\n');
    document.writeln('.ButtonStd2 .Centre a {padding-top:7px; padding-bottom:9px;}\n');
    document.writeln('.ButtonStdSmall .Centre {height:19px;}\n'); 
  }
  document.writeln('/*]]>*/\n</style>\n');
}

function getYear() {
  var d = new Date();
  document.getElementById('GetYear').innerHTML = d.getFullYear();
}

// hide 0 or one element and show another element, indicated by id
// css width property is required for every switchable element. Can be in pixels or percents
function hideShow(id_hide, id_show, type) {
  switch (type) {
    case 'fade':
      if (id_hide == "-") {//only show, but wait to synchronize with other elements
        window.setTimeout("$('#" + id_show + "').fadeIn(400);",450);
      } else {
        $('#' + id_hide).fadeOut(200, function(){
          $('#' + id_show).fadeIn(400);
        });
      }
    break;
    case 'slide':
      if (id_hide == "-") {
        window.setTimeout("$('#" + id_show + "').slideDown(400);",450);
      } else {
        $('#' + id_hide).slideUp(200, function(){
          $('#' + id_show).slideDown(400);
        });
      }
    break;
    case 'blink':
      $('#' + id_hide).hide();
      $('#' + id_show).show();
    break;
  }
}

//show single element with given id
function show(id_show, type) {
  switch (type) {
    case 'fade':
      $('#' + id_show).fadeIn(400);
    break;
    case 'slide':
      $('#' + id_show).slideDown(400);
    break;
    case 'blink':
      $('#' + id_show).show();
    break;
  }
}

//hide single element with given id
function hide(id_hide, type) {
  switch (type) {
    case 'fade':
      $('#' + id_hide).fadeOut(200);
    break;
    case 'slide':
      $('#' + id_hide).slideUp(200);
    break;
    case 'blink':
      $('#' + id_hide).hide();
    break;
  }
}

// hide 0 or more elements and show 0 or more oter elements, indicated by id
// css width property is required for every switchable element. Can be in pixels or percents
// use example1: hideShowList(["id1","id2","id3"],["id6"],"blink");
// use example2: hideShowList(["-"],["id6","id7","id8"],"fade");
function hideShowList(hide_array, show_array, type) {
  if (hide_array[0] != '-') {
    for(var i=0; i<hide_array.length; i++) {
      hide(hide_array[i], type);
    }
  }
  
  if (show_array[0] != '-') {
    for(var i=0; i<show_array.length; i++) {
      show(show_array[i], type);
    }
  }
}

//Questionnaire pages - ADMIN
var drag_array = new Array();

function initQstDrag() {
  var parent_length = $('.QstDrag').length
  for (var i = 0; i < parent_length; i++) {
    var div_length = $('.QstDrag:eq(' + i + ')').find('.DragSection').length
    for (var k = 0; k < div_length; k++) {
      drag_array[$('.QstDrag:eq(' + i + ')').find('.DragSection:eq(' + k + ')').html()] = i
      //alert($('.QstDrag:eq(' + i + ')').find('.DragSection:eq(' + k + ')').html())
    }
  }

  var drop_area_content = '';
  var drop_index = 0;
  do {
    drop_area_content = (drop_area_content + '<div class="DropZone"><h3><div class="RemoveQstHeading"></div><span>' + $('#HeadingHiddenFields input:eq(' + drop_index + ')').val() + '</span></h3></div>')
    drop_index++;
  }
  while ($('#HeadingHiddenFields input:eq(' + drop_index + ')').val() != '' && drop_index <= 11);
  $('.QuestionnaireDrop').html(drop_area_content)

  var drop_index2 = 0;
  $('.QuestionnaireDrop .DropZone').each(function() {
    var drop_str = $('.HeadingContentHiddenFields input:eq(' + drop_index2 + ')').val()

    var drop_content_array = new Array();
    drop_content_array = drop_str.split(',')
    for (var i = 0; i < (drop_content_array.length - 1); i++) {
      $('#' + drop_content_array[i]).addClass('RemoveMe').clone().removeClass('RemoveMe').appendTo($(this));
      $('.RemoveMe').remove();
    }
    drop_index2++;
  });
  assignHeadingEffects();
  check_qst_validation();
  assignDragDivEffects();

    $('.QstAddNewHeading input').keyup(function() {
      if ($('.DropZone').length >= 12) {
        $(this).animate({ width: '150px' }, 400)
        $(this).next('.PlusButton').animate({ width: '0px' }, 400)
      }
      if ($('.DropZone').length >= 12) {
        $('.QstAddNewHeading span').stop(true,true).empty().css('display','block').html('Maximum of 12').fadeOut(2500)
        $('.QstAddNewHeading input').removeAttr('value')
      }
      
    });

    $('.QstAddNewHeading .PlusButton').click(function() {
      if ($('.QstAddNewHeading input').val() != '' && $('.DropZone').length < 12) {
        $('.QuestionnaireDrop').html($('.QuestionnaireDrop').html() + '<div class="DropZone"><h3><div class="RemoveQstHeading"></div><span>' + $('.QstAddNewHeading input').val() + '</span></h3></div>')
        $('.QuestionnaireDrop .DropZone:last').css('display', 'none').slideDown(500, function() {
          assignHeadingEffects();
          $('.DropZone').unbind('dropstart').unbind('drop').unbind('dropend')
          bindDrop();
          check_qst_validation()
        })
        $('.DragSection').unbind('dragstart').unbind('drag').unbind('dragend')
        bindDrag();
      }
      if ($('.DropZone').length >= 12) {
        $('.QstAddNewHeading input').animate({ width: '150px' }, 400)
        $('.QstAddNewHeading .PlusButton').animate({ width: '0px' }, 400)
      }
      $('.QstAddNewHeading input').removeAttr('value')
    });
  bindDrag()
}

function assignDragDivEffects() {
  $('.DragSection').click(function() {
    $('.QstDrag .Selected').removeClass('Selected')
    $(this).addClass('Selected')
  });
  $('.DragSection').hover(function() {
    $(this).find('div').removeAttr('style').clone().appendTo('.MainRight').show(200)
  }, (function() {
    $('.MainRight .NormHelpText').remove()
  }));
}

function assignHeadingEffects() {
  $('.DropZone h3').hover(function() {
    $(this).find('.RemoveQstHeading').stop(true, true).fadeIn(400)
  }, (function() {
    $(this).find('.RemoveQstHeading').stop(true, true).fadeOut(400)
  }));

  $('.RemoveQstHeading').click(function() {
    $(this).parent().parent().find('.DragSection').each(function() {
      var put_here = drag_array[$(this).find('span').html()]
      $(this).clone(true).prependTo($('.QstDrag:eq(' + put_here + ')'))
      $(this).remove()
    });
    $(this).parent().parent().remove()
    $('.QstAddNewHeading input').animate({ width: '130px' }, 400)
    $('.QstAddNewHeading .PlusButton').animate({ width: '12px' }, 400)

    $('.QuestionnaireDrop .DropZone').unbind('dropstart').unbind('drop').unbind('dropend')
    bindDrop();
    check_qst_validation();
  });

  $('.DropZone h3').dblclick(function() {
    if ($(this).find('input').length == 0) {
      $(this).html($(this).html() + '<input type="text" value="' + $(this).find('span').html() + '" />')
      $(this).find('span').empty()
      $(this).find('input').focus()
      $('.DropZone h3 input').blur(function() {
        $(this).parent().find('span').html($(this).val())
        $(this).remove()
        assignHeadingEffects();
      })
    }
  });
}

var scale_var = 0;
function check_qst_validation() {
  var scale_time = ($('.ScaleTimeHidden input').attr('Value')) / 6

  var one_scale = '';
  var scale_length = $('.DropZone .DragSection').length
  $('.DropZone').each(function() {
    if ($(this).find('.DragSection').length >= 1) {
      one_scale = one_scale + '1'
    }
    else {
      one_scale = one_scale + '0'
    }
  });
  //alert(one_scale)
  if (one_scale.indexOf('0') != -1) {
    $('.QstValidation').removeClass('QstValid').addClass('QstInvalid').find('span').html('You have selected ' + scale_length + ' scales.<br /><b>Please add at least one scale to each profile heading.</b>')
  }
  else {
    scale_var = 1;
    if (scale_length >= 18) {
      if (scale_length % 3 == 0) {
        if (scale_length >= 30) {
          $('.QstValidation').removeClass('QstInvalid').addClass('QstValid').find('span').html('You have selected ' + scale_length + ' scales.<br />This questionnaire will work and will take most people ' + (scale_time * scale_length) + ' minutes to complete - we suggest you stop there.')
        }
        else {
          $('.QstValidation').removeClass('QstInvalid').addClass('QstValid').find('span').html('You have selected ' + scale_length + ' scales.<br />This questionnaire will work and will take most people ' + (scale_time * scale_length) + ' minutes to complete.')
        }
      }
      else {
        $('.QstValidation').removeClass('QstValid').addClass('QstInvalid').find('span').html('You have selected ' + scale_length + ' scales.<br />You need to add another ' + (3 - (scale_length % 3)) + ' scale(s) before your questionnaire will work.')
      }
    }
    else {
      if (scale_length == 9 || scale_length == 12 || scale_length == 18) {
        $('.QstValidation').removeClass('QstInvalid').addClass('QstValid').find('span').html('You have selected ' + scale_length + ' scales.<br />This questionnaire will work and will take most people ' + (scale_time * scale_length) + ' minutes to complete.')
      }
      else {
        var this_many = 0;
        if (scale_length < 9) {
          this_many = 9 - scale_length;
        }
        else if (scale_length < 12) {
          this_many = 12 - scale_length;
        }
        else if (scale_length < 18) {
          this_many = 18 - scale_length;
        }
        $('.QstValidation').removeClass('QstValid').addClass('QstInvalid').find('span').html('You have selected ' + scale_length + ' scales.<br />You must add another ' + this_many + ' scale(s) before your questionnaire will work.')
      }
    }
  }
//  if (scale_var == 0) {
//    $('.QstValidation').removeClass('QstValid').addClass('QstInvalid').find('span').html('You have selected ' + scale_length + ' scales.<br />Please start making your scale selections.')
//    scale_var = 1;
//  }

}

var $drag;
function bindDrag() {
  $(function() {
    $(".DragSection")
		.bind("dragstart", function(event) {
		  $drag = $(this), $proxy = $drag.clone();
		  $drag.css("opacity", "0.5");
		  $drag.addClass('Dragging')
		  return $proxy.appendTo(document.body).addClass("ghost");
		})
		.bind("drag", function(event) {
		  $(event.dragProxy).css({
		    position: "absolute",
		    cursor: "move",
		    zIndex: "1000",
		    left: event.offsetX,
		    top: event.offsetY,
		    opacity: "0.5"
		  });
		})
		.bind("dragend", function(event) {
		  $(event.dragProxy).fadeOut("normal", function() {
		    $(this).remove();
		  });
		  $('.Dragging').removeClass('Dragging')
		  $(this).css("opacity", "1");
		});
    $('.QstDrag')
		.bind("dropstart", function(event) {
		  if (this == event.dragTarget.parentNode) return false;
		  $(this).addClass("active");
		  $(this).prev("h3").css('color','#F90');
		})
		.bind("drop", function(event) {
		  $('.QstDrag:eq(' + drag_array[$('.Dragging').html()] + ')').prepend(event.dragTarget);
		  var drop_array = new Array()
		  for (var d = 0; d < $('.QstDrag:eq(' + drag_array[$('.Dragging').html()] + ') .DragSection').length; d++) {
		    drop_array[d] = $('.QstDrag:eq(' + drag_array[$('.Dragging').html()] + ') .DragSection:eq(' + d + ')').html()
		  }
		  check_qst_validation();
		})
		.bind("dropend", function(event) {
		  $(this).removeClass("active");
		  $(this).prev("h3").css('color', '#999');
		});
  });
  bindDrop()
}

function bindDrop() {
  $(function() {
    $('.QuestionnaireDrop .DropZone')
		.bind("dropstart", function(event) {
		  if (this == event.dragTarget.parentNode) return false;
		  $(this).addClass("active");
		  $(this).parent().css('borderColor','#F90')
		})
		.bind("drop", function(event) {
		  $(this).append(event.dragTarget);
		  $(this).find('.Dragging:last').css('display', 'none').slideDown(500)
		  check_qst_validation();
		  $('.QuestionnaireDrop .DropZone').unbind('dropstart').unbind('drop').unbind('dropend')
		  bindDrop()
		})
		.bind("dropend", function(event) {
		  $(this).removeClass("active");
		  $(this).parent().css('borderColor', '#CCC')
		});
  });
}

function resetQstScales() {
  $('.QuestionnaireDrop .DropZone .DragSection').each(function() {
  var put_here = drag_array[$(this).html()]
    $(this).clone().prependTo($('.QstDrag:eq(' + put_here + ')'))
    $(this).remove()
  });
  $('.DragSection').unbind('dragstart').unbind('drag').unbind('dragend')
  bindDrag();
  $('.QuestionnaireDrop .DropZone').unbind('dropstart').unbind('drop').unbind('dropend')
  bindDrop()
  check_qst_validation();

}

function getQstString() {
    if ($('.QstInvalid').length >= 1) {
        $('.QstValidation input').attr('value', 'invalid')
    }
    if ($('.QstValid').length >= 1) {
        $('.QstValidation input').attr('value', 'valid')
    }
    $('.HeadingContentHiddenFields input').removeAttr('value')
    $('.HeadingHiddenFields input').removeAttr('value')
  var parent_index = 0;  
  var this_index = 0;
  $('.QuestionnaireDrop .DropZone').each(function() {
    $('.HeadingHiddenFields input:eq(' + parent_index + ')').val($(this).find('span:eq(0)').html())
    $(this).find('.DragSection').each(function() {
      $('.HeadingContentHiddenFields input:eq(' + this_index + ')').attr('value', ($('.HeadingContentHiddenFields input:eq(' + this_index + ')').attr('value') + $(this).attr('id') + ','))
    });
    this_index++;
    parent_index++;
  });
}


//Assign Clients - Multiple areas in ADMIN (creates right hand comlumn and splits the group evenly)
//warning - may not work when more FormFields added to the page
function initAssign() {
  $('.FormRight .FormField').html('<table class="CbVerticalList"></table>')
  $('.FormLeft tr:odd').clone(true).appendTo('.FormRight .FormField table')
  $('.FormLeft tr:odd').remove()
}
function assignSelectAll() {
  $('.CbVerticalList input').attr('checked', 'checked')
}
function assignDeselectAll() {
  $('.CbVerticalList input').removeAttr('checked')
}

//length info (Jquery version... works when repeater is involved)
function initJQCheckLength(max_length) {
  
  $('.JQCheckLength').each(function() {
    var current_length = $(this).attr('value').length;
    if (current_length == 0) {
      $(this).parent().after('<div class="LengthInfo">' + MaximumTextLengthIsXXCharacters.replace("[XX]", max_length) + '</div>')      
    } else {
      $(this).parent().after('<div class="LengthInfo">' + YouMayEnterXXMoreCharacters.replace("[XX]", max_length - current_length) + '</div>')
    }
  });
  
  $('.JQCheckLength').keyup(function() {
    var current_length = $(this).attr('value').length
    var current_element = $(this).closest('.FormBox').find('.LengthInfo')
    if (current_length == 0) {
      current_element.html(MaximumTextLengthIsXXCharacters.replace("[XX]", max_length));
    }
    if (current_length >= 1) {
      var characters_left = max_length - current_length;
      if (characters_left < 0) characters_left = 0;
      current_element.html(YouMayEnterXXMoreCharacters.replace("[XX]", characters_left));
    }
    if (current_length > max_length) {
      var temp = $(this).attr('value')
      $(this).attr('value', temp.substr(0, max_length));
    }
  })
};

//Assessment Template pages - ADMIN
function initAssess() {
//  var span_total = '0'
//  if ($('.AssessTable .Col1h input').length <= 0) {
//    $('.AssessTable .Col3h span').each(function() {
//    span_total = (parseFloat(span_total) + parseFloat($(this).html())).toFixed(2);
//    });
//  }
//  else {
//    $('.AssessTable .Col1h input:checked').each(function() {
//    span_total = (parseFloat(span_total) + parseFloat($(this).closest('tr').find('.Col3h span').html())).toFixed(2);
//    });
//  }
//  $('.AssessTotal span').html(span_total)
  
  $('.AssessTable .Col1h input:checked').each(function() {

  $(this).closest('tr').next('tr').next('tr').find('.AssessDropHolder').css('display','block')
    
  });
  
  $('.AssessTable input').click(function() {
    if ($(this).is(':checked')) {
      $(this).closest('tr').next('tr').next('tr').find('.AssessDropHolder').slideDown(300)
      //$('.AssessTotal span').html((parseFloat($(this).closest('tr').find('.Col3h span').html()) + parseFloat($('.AssessTotal span').html())).toFixed(2))
    }
    else {
      $(this).closest('tr').next('tr').next('tr').find('.AssessDropHolder').slideUp(200)
      //$('.AssessTotal span').html((parseFloat($('.AssessTotal span').html()) - parseFloat($(this).closest('tr').find('.Col3h span').html())).toFixed(2))
    }
  })
  
  $('.AssessArrowUp,.AssessArrowDown').css('opacity','0.2')

  $('.AssessTable .AssessArrowUp,.AssessArrowDown').hover(function() {
    $(this).stop(true,true).animate({opacity:'1'},200)
  }, function() {
    $(this).animate({ opacity: '0.2' }, 100)
  });
  $('.AssessTable .AssessArrowUp').click(function() {
    if ($('.AssessTable tr').index($(this).closest('tr')) != 0) {
      $(this).closest('tr').addClass('RemoveMe').clone(true).removeClass().insertBefore($(this).closest('tr').prev('tr').prev('tr'))
      $(this).closest('tr').next('tr').addClass('RemoveMe').clone(true).removeClass().insertBefore($(this).closest('tr').prev('tr').prev('tr'))
      $('.AssessArrowUp').css({ opacity: '0.2' })
      $('.RemoveMe').remove()
    }
  });
  $('.AssessTable .AssessArrowDown').click(function() {
  if ($('.AssessTable tr').index($(this).closest('tr')) != ($('.AssessTable tr').length - 2)) {
      $(this).closest('tr').addClass('RemoveMe').clone(true).removeClass().insertAfter($(this).closest('tr').next('tr').next('tr'))
      $(this).closest('tr').prev('tr').addClass('RemoveMe').clone(true).removeClass().insertAfter($(this).closest('tr').next('tr').next('tr'))
      $('.AssessArrowDown').css({ opacity: '0.2' })
      $('.RemoveMe').remove()
    }
  });

}

function getAssessOrder() {
  $('.AssessTable .Col2h input').each(function() {
  $(this).val($('.AssessTable .Col2h input').index(this))
  //alert($(this).val())
  });

}

//Score band slider on add/edit campaign
function initRejectSlider() {
  $("div.RejectSliderInner").each(function() {
    var min_value = $(this).parent().find('input').eq(0).val();
    var max_value = $(this).parent().find('input').eq(1).val();
    if (min_value == "") min_value = 1;
    if (max_value == "") max_value = 10;

    var patch_width = ((min_value-1)*29)-5;
    if (patch_width < 0) patch_width = 0;
    $(this).parent().find('.LeftEndPatch').css("width", patch_width );
    
    $(this).slider({
      values: [min_value, max_value],
      range: true,
      min: 1,
      max: 10,
      step: 1,
      change: function(event, ui) {
        $(this).parent().find('input').eq(0).val(ui.values[0]);
        $(this).parent().find('input').eq(1).val(ui.values[1]);
      },
      slide: function(event, ui) {
        var patch_width = ((ui.values[0]-1)*29)-5;
        if (patch_width < 0) patch_width = 0;
        $(this).parent().find('.LeftEndPatch').css("width", patch_width);
      }
    }); //end .slider
    
  });
}

function initEQ() {
  $('#EQSliders .EQTable:last .EQSlider').each(function() {
    var eq_value = $(this).find('input').val();
    $(this).slider({
      value: eq_value,
      orientation: "vertical",
      min: 1,
      max: 5,
      step: 1,
      slide: function(event, ui) {
        $(this).parent().parent().find('.EQExtreme').removeClass('EQExtreme')
        $(this).parent().parent().find('.CurrentScale').removeClass('CurrentScale')
        $(this).parent().addClass('CurrentScale')
        $(this).removeClass('StarScale1').removeClass('StarScale2').removeClass('StarScale3').removeClass('StarScale4').removeClass('StarScale5')
        $(this).addClass('StarScale' + ui.value)
        $(this).find('input').val(ui.value)

        //Rule 1. Either side of each slider must be within two of the current slider
        var neighbour_left = parseInt($(this).parent().prev('.EQCol').find('input').val())
        var neighbour_right = parseInt($(this).parent().next('.EQCol').find('input').val())
        var this_slider = $(this).find('input').val()
        var target_slider_left = $(this).parent().prev('.EQCol').find('.EQSlider')
        var target_slider_right = $(this).parent().next('.EQCol').find('.EQSlider')
        if ((neighbour_left + 2) < this_slider) {
          target_slider_left.removeClass('StarScale1').removeClass('StarScale2').removeClass('StarScale3').removeClass('StarScale4').removeClass('StarScale5')
          target_slider_left.addClass('StarScale' + (neighbour_left + 1))
          target_slider_left.slider('option', 'value', (neighbour_left + 1))
          $(this).parent().prev('.EQCol').find('input').val(neighbour_left + 1)
        }
        if ((neighbour_left - 2) > this_slider) {
          target_slider_left.removeClass('StarScale1').removeClass('StarScale2').removeClass('StarScale3').removeClass('StarScale4').removeClass('StarScale5')
          target_slider_left.addClass('StarScale' + (neighbour_left - 1))
          target_slider_left.slider('option', 'value', (neighbour_left - 1))
          $(this).parent().prev('.EQCol').find('input').val(neighbour_left - 1)
        }
        if ((neighbour_right + 2) < this_slider) {
          target_slider_right.removeClass('StarScale1').removeClass('StarScale2').removeClass('StarScale3').removeClass('StarScale4').removeClass('StarScale5')
          target_slider_right.addClass('StarScale' + (neighbour_right + 1))
          target_slider_right.slider('option', 'value', (neighbour_right + 1))
          $(this).parent().next('.EQCol').find('input').val(neighbour_right + 1)
        }
        if ((neighbour_right - 2) > this_slider) {
          target_slider_right.removeClass('StarScale1').removeClass('StarScale2').removeClass('StarScale3').removeClass('StarScale4').removeClass('StarScale5')
          target_slider_right.addClass('StarScale' + (neighbour_right - 1))
          target_slider_right.slider('option', 'value', (neighbour_right - 1))
          $(this).parent().next('.EQCol').find('input').val(neighbour_right - 1)
        }

        //Rule 2. Only one direction change (point of influx) is allowed
        var temp_str = '';
        $(this).parent().parent().find('.EQCol').each(function() {
          var neighbour_left2 = parseInt($(this).prev('.EQCol').find('input').val())
          var neighbour_right2 = parseInt($(this).next('.EQCol').find('input').val())
          var this_slider2 = $(this).find('input').val()
          if ((neighbour_left2 > this_slider2) && (neighbour_right2 > this_slider2)) {
            $(this).addClass('EQExtreme')
            temp_str = (temp_str + 1)
          }
          if ((neighbour_left2 < this_slider2) && (neighbour_right2 < this_slider2)) {
            $(this).addClass('EQExtreme')
            temp_str = (temp_str + 1)
          }
        });
        if (temp_str.length > 1) {
          var influx_point = $('.EQExtreme:not(.CurrentScale)').find('.EQSlider')
          var adjusted_slider_left = parseInt($('.EQExtreme:not(.CurrentScale)').prev('.EQCol').find('input').val())
          var adjusted_slider_right = parseInt($('.EQExtreme:not(.CurrentScale)').next('.EQCol').find('input').val())
          var adjusted_slider = Math.round((adjusted_slider_left + adjusted_slider_right) / 2)

          influx_point.removeClass('StarScale1').removeClass('StarScale2').removeClass('StarScale3').removeClass('StarScale4').removeClass('StarScale5')
          influx_point.addClass('StarScale' + (adjusted_slider))
          influx_point.slider('option', 'value', (adjusted_slider))
          $('.EQExtreme:not(.CurrentScale)').find('input').val(adjusted_slider)

        }
        //Rule 3. Must be at least one minimum and one maximum value
        var is_valid = $(this).parent().parent().find('.EQValidation')
        var temp_str = ''
        $(this).parent().parent().find('.EQSlider').each(function() {
          temp_str = (temp_str + $(this).find('input').val() + ',')
        });
        if ((temp_str.lastIndexOf('1') != -1) && (temp_str.lastIndexOf('5') != -1)) {
          is_valid.removeClass('EQInvalid')
          is_valid.addClass('EQValid')
          is_valid.find('div').html('This matching-score range is all good.')
        }
        else {
          $(this).parent().parent().find('.EQValidation').removeClass('EQValid')
          $(this).parent().parent().find('.EQValidation').addClass('EQInvalid')
          $(this).parent().parent().find('.EQValidation div').html('This matching-score range needs a max and min value.')
        }
      }
    });
    $(this).addClass('StarScale' + eq_value)
  });
}

function initvalidateEQ() {

  $('#EQSliders .EQTable').each(function() {
    var temp_str = ''
    $(this).find('.EQSlider').each(function() {
      temp_str = (temp_str + $(this).find('input').val() + ',')
    });
    if ((temp_str.lastIndexOf('1') != -1) && (temp_str.lastIndexOf('5') != -1)) {
      $(this).find('.EQValidation').removeClass('EQInvalid')
      $(this).find('.EQValidation').addClass('EQValid')
      $(this).find('.EQValidation div').html('This matching-score range is all good.')
    }
    else {
      $(this).find('.EQValidation').removeClass('EQValid')
      $(this).find('.EQValidation').addClass('EQInvalid')
      $(this).find('.EQValidation div').html('This matching-score range needs a max and min value.')
    }
  });
}

$(document).ready(function() {

  initvalidateEQ();

  //For when there are two separate forms on one page (home page)
  $(".ForJQDiv input").keypress(function(event) {
    if (event.keyCode == 13) {
      $(".Default").click();
      return false;
    } else {
      return true
    }
  });

  //Multiple places - drops down a dropdown box when radio selected
  $('.JQOtherDropDown').each(function() {
    if ($(this).find('option:selected').html().toLowerCase().lastIndexOf('other') == 0) {
      $(this).parent().next('.JQHiddenField').css('display', 'block')
    }
  });

  $('.JQOtherDropDown').click(function() {
    if ($(this).find('option:selected').html().toLowerCase().lastIndexOf('other') == 0) {
      $(this).parent().next('.JQHiddenField').slideDown(300)
    } else {
      $(this).parent().next('.JQHiddenField').slideUp(300)
    }
  });


  $('.JQOtherRadio').each(function() {
    if ($(this).find('input').is(':checked') && $(this).parent().parent().find('.JQOtherRadio').index(this) == 0) {
      $(this).parent().parent().next('.JQHiddenField').css('display', 'block')
    }
  });

  $('.JQOtherRadio').click(function() {
    if ($(this).parent().parent().find('.JQOtherRadio').index(this) == 0) {
      if ($(this).find('input').is(':checked')) {
        $(this).parent().parent().next('.JQHiddenField').slideDown(300)
      }
      else {
        $(this).parent().parent().next('.JQHiddenField').slideUp(300)
      }
    }
    else {
      $(this).parent().parent().next('.JQHiddenField').slideUp(300)
    }
  });

  //Questionnaire matchings page - ADMIN



  $(".Starslider").each(function() {
    var slider_value = $(this).parent().find('.StarHiddenField input').val()
    $(this).slider({
      value: slider_value,
      min: 0,
      max: 6,
      step: 1,
      slide: function(event, ui) {
        if (ui.value == 0) {
          $(this).parent().find('span').removeClass('Active')
        }
        $(this).parent().find('span:gt(' + (ui.value - 1) + ')').removeClass('Active')
        $(this).parent().find('span:lt(' + (ui.value) + ')').addClass('Active')
        if (ui.value <= 5) {
          $(this).parent().find('.StarHiddenField input').val(ui.value)
        }
      }
    });
    $(this).parent().find('span:lt(' + (slider_value) + ')').addClass('Active')

  });

  //Assign scales - ADMIN
  $('.NormTable .Col2 span, .NormTable .Col7 span').hover(function() {
    $(this).next('.NormHelpText').removeAttr('style').clone().appendTo('.MainRight').show(200)
  }, (function() {
    $('.MainRight .NormHelpText').remove()
  }));

  $('.DropZoneView .DragSection').hover(function() {
    $(this).find('.NormHelpText').removeAttr('style').clone().appendTo('.MainRight').show(200)
  }, (function() {
    $('.MainRight .NormHelpText').remove()
  }));


  $('.ScaleTable input').focus(function() {
    $('.ScaleTable tr').removeClass('ScaleSelected')
    $(this).closest('tr').addClass('ScaleSelected')
  }).blur(function() {
    $('.ScaleTable tr').removeClass('ScaleSelected')
  });

  //Travelling assessment material - various prongs - CANDIDATE
  var scroll_position = 0;
  var screen_size = 0;
  var question_height = $('.TravellingVersion').height();
  $(window).scroll(function() {
    if (window.innerHeight) { screen_size = window.innerHeight }
    else if (document.documentElement.clientHeight) { screen_size = document.documentElement.clientHeight }
    else (screen_size = document.body.clientHeight)

    if (document.documentElement.scrollTop) { scroll_position = document.documentElement.scrollTop }
    else if (window.pageYOffset) { scroll_position = window.pageYOffset }
    else (scroll_position = document.body.scrollTop)

    var should_scroll = 1;
    if ((question_height + 250) >= screen_size) { should_scroll = 0 }


    if (scroll_position >= 190 && should_scroll == 1) {
      if ($('.TravellingVersion').length == 1) {
        if (!msie_old) {
          $('.TravellingVersion').clone().insertAfter('.TravellingVersion')
          $('.TravellingVersion').eq(0).css({ position: 'fixed', top: '0px', zIndex: '18' })
          $('.TravellingVersion').eq(1).find('.TestTop, .TestBottom').css('display', 'none')
        }
      }
    }
    if (scroll_position <= 190) {
      if ($('.TravellingVersion').length > 1) {
        $('.TravellingVersion').eq(1).find('.TestTop, .TestBottom').css('display', 'block')
        $('.TravellingVersion').eq(0).remove()
      }
    }
  });

  $('.FormPopUp').hover(
    function() {
      $(this).find('.FormPopUpDiv').show(300);
    },
    function() {
      $(this).find('.FormPopUpDiv').stop(true, true).hide(300);
      //back to original state
    });


  $('.GroupEditBox input').keypress(function() {
    var radio_length = ($(this).parent().parent().find('.Radio input').length) - 1;
    if ($(this).is(':not(.ActiveInput)')) {
      $('.GroupEditBox input').removeClass('ActiveInput')
      $(this).addClass('ActiveInput')
    }
    $('.GroupEditBox input:not(.ActiveInput)').attr('value', '')
    if ($(this).closest('.FormBox').find('.Radio input').index($(this).closest('.FormBox').find('.Radio input:checked')) != radio_length) {
      $(this).closest('.FormBox').find('.Radio:last input').attr('checked', 'checked')
    }
  });

  $('.DiversityGroup .Radio input').click(function() {
    $('.GroupEditBox input').removeAttr('value')
  });


  //Form fields on focus highlight - selects, textareas, textboxes
  $("select.WithFocusHighlight, textarea.WithFocusHighlight, input.WithFocusHighlight").focus(function() {
    $(this).closest(".FormBox").addClass("FormBoxFocusHighlighted");
  });
  $("select.WithFocusHighlight, textarea.WithFocusHighlight, input.WithFocusHighlight").blur(function() {
    $(this).closest(".FormBox").removeClass("FormBoxFocusHighlighted");
  });

  //Highlight on focus - single checkbox/radiobutton
  $("span.WithFocusHighlight > input").focus(function() {
    $(this).closest(".FormBox").addClass("FormBoxFocusHighlighted");
  });
  $("span.WithFocusHighlight > input").click(function() { //added onclick because of safari
    $(this).focus();
  });
  $("span.WithFocusHighlight > input").blur(function() {
    $(this).closest(".FormBox").removeClass("FormBoxFocusHighlighted");
  });

  //Highlight on focus - radiobutton/checkbox lists
  $("table.WithFocusHighlight").find("input").focus(function() {
    $(this).closest(".FormBox").addClass("FormBoxFocusHighlighted");
  });
  $("table.WithFocusHighlight").find("input").click(function() { //added onclick because of safari
    $(this).focus();
  });
  $("table.WithFocusHighlight").find("input").blur(function() {
    $(this).closest(".FormBox").removeClass("FormBoxFocusHighlighted");
  });

  //form fields validation highlight - parent box
  $(".WithFocusHighlight").closest(".FormBox").find(".ValidationInfo").each(function() {
    $(this).closest(".FormBox").addClass("FormBoxValidationHighlighted");
  });

  //form fields validation highlight - each field except for radio and checkbox
  $(".WithFocusHighlight").closest(".FormBox").find(".ValidationInfo").each(function() {
    if ($(this).closest(".InnerFormBox").length == 1) {
      $(this).closest(".InnerFormBox").find("input[type!='radio'][type!='checkbox']").addClass("InputFieldValidationHighlighted");
      $(this).closest(".InnerFormBox").find("select").addClass("InputFieldValidationHighlighted");
      $(this).closest(".InnerFormBox").find("textarea").addClass("InputFieldValidationHighlighted");
    } else {
      $(this).closest(".FormBox").find("input[type!='radio'][type!='checkbox']").addClass("InputFieldValidationHighlighted");
      $(this).closest(".FormBox").find("select").addClass("InputFieldValidationHighlighted");
      $(this).closest(".FormBox").find("textarea").addClass("InputFieldValidationHighlighted");
    }
  });

});  //end DOM ready section


//information box on validation image rollover - old validation mechanism
function validationInfo(operation, img_ref){
  if(operation == "show") {
    if (img_ref.alt.length > 0) img_ref.previousSibling.innerHTML = img_ref.alt;
    img_ref.alt = "";
    img_ref.previousSibling.style.display = "block";
  }
  if(operation == "hide") img_ref.previousSibling.style.display = "none";
}

//Divide admin global nav tabs into 1, 2 or 3 rows;
function updateNavigation () { 
  var max_number_of_tabs_in_single_row = 10;
  var number_of_tabs = $(".GlobalNavInner span.Active, .GlobalNavInner span.Inactive").length;
  if (number_of_tabs <= max_number_of_tabs_in_single_row ) { //make one row
    $(".GlobalNavInner").wrapInner("<div class=\"RowSingle\"></div>");
  } else {
    var html_begining = '<div class="RowSingle">';
    var html_middle_to_replace = 'fdsa';
    var html_middle = '</div><div class="RowSingle">';
    var html_end = '</div>';
    var inner_content = '';
    var divider_pos = number_of_tabs / (max_number_of_tabs_in_single_row - 1);
    var number_of_rows = Math.ceil(divider_pos);
    var divide_after = Math.floor(number_of_tabs/number_of_rows) - 1; //-1 because eq is 0 based
    
    if (number_of_rows == 2) { //make two rows
      $(".GlobalNavInner span.Between").eq(divide_after-1).after(html_middle_to_replace);
      inner_content = $(".GlobalNavInner").html();
      inner_content = html_begining + inner_content.replace(html_middle_to_replace, html_middle) + html_end;
      $(".GlobalNavInner").html(inner_content);
    }  
    if (number_of_rows > 2) { //make three rows
      $(".GlobalNavInner span.Between").eq(divide_after-1).after(html_middle_to_replace);
      $(".GlobalNavInner span.Between").eq(divide_after*2).after(html_middle_to_replace);
      inner_content = $(".GlobalNavInner").html();
      inner_content = inner_content.replace(html_middle_to_replace, html_middle)
      inner_content = html_begining + inner_content.replace(html_middle_to_replace, html_middle) + html_end;
      $(".GlobalNavInner").html(inner_content);
    }  
  }
}

/* ADMIN access page */
function selectAllAccessItem(button_ref) {
  $(button_ref).parent().parent().find("input").attr("checked", "checked");
  return false;
}

function deselectAllAccessItem(button_ref) {
  $(button_ref).parent().parent().find("input").removeAttr("checked");
  return false;
}

function selectAllAccessGlobal() {
  $("#ForJSAllCheckboxesInside").find("input").attr("checked", "checked");
  return false;
}

function deselectAllAccessGlobal() {
  $("#ForJSAllCheckboxesInside").find("input").removeAttr("checked");
  return false;
}
/* end ADMIN access page */

function testPassword(passwd, target_message_id) {
	var score   = 0;
	var verdict = "";
  var description = new Array();
      description[0] = "Too short – longer is better";
      description[1] = "Bit feeble – mix it up more";
      description[2] = "Not bad – use more symbols";
      description[3] = "Sturdy – well done";
	
	if (passwd.length <= 3 || !passwd.length) {
	  document.getElementById(target_message_id).getElementsByTagName('span')[0].innerHTML = description[0];	
	  return;
	}

	if (passwd.length >= 5 && passwd.length <= 6)  score += 5;
	if (passwd.length >= 7 && passwd.length <= 8)  score += 7;
	if (passwd.length >= 9 && passwd.length <= 10) score += 9;
	if (passwd.length >= 11)                       score += 11;

	if (passwd.match(/[a-f]/)) score += 2;
	if (passwd.match(/[g-k]/)) score += 2;
	if (passwd.match(/[l-q]/)) score += 2;
	if (passwd.match(/[r-u]/)) score += 2;
	if (passwd.match(/[v-z]/)) score += 2;
	
	if (passwd.match(/[A-F]/)) score += 2;
	if (passwd.match(/[G-K]/)) score += 2;
	if (passwd.match(/[L-Q]/)) score += 2;
	if (passwd.match(/[R-U]/)) score += 2;
	if (passwd.match(/[V-Z]/)) score += 2;
	
	if (passwd.match(/[0-1]/)) score += 2;
	if (passwd.match(/[2-3]/)) score += 2;
	if (passwd.match(/[4-5]/)) score += 2;
	if (passwd.match(/[6-7]/)) score += 2;
	if (passwd.match(/[8-9]/)) score += 2;
	
	if (passwd.match(/.[&,*,\"]/))  score += 3;
	if (passwd.match(/.[$,%,-]/))   score += 3;
	if (passwd.match(/.[!,@,#]/))	  score += 3;
	if (passwd.match(/.[?,+,_,;]/)) score += 3;
	if (passwd.match(/.[^,=,~,:]/)) score += 3;
	  
	if (score <= 15)                 verdict = description[1];
  if (score >= 16 && score <= 19)  verdict = description[2];
	if (score >= 20)                 verdict = description[3];

  if (verdict.length > 0)
	  document.getElementById(target_message_id).getElementsByTagName('span')[0].innerHTML = verdict;
}

/********* WARNING POPUP BEFORE TIMED TESTS functions *********/
function blackOutPopUp(source_popup_id){
  var body_width = $("body").width();
  if (body_width < 996) {body_width = 996;}
  var body_height = $(document).height();
  var box_pos = parseInt(body_width/2) - 200;
  var top_position = getScrollOffset() + 150;  
  
  document.getElementById("BlackOutPopUpBoxTarget").innerHTML = document.getElementById(source_popup_id).innerHTML;
   
  //show the CoverLayer and the popup box from the master page with content copied from content page
  $("#CoverLayer")
    .css({"width":body_width, "height":body_height, "opacity":0, "display":"block"})
    .animate({opacity:0.6}, 1000, function(){
       $("#BlackOutPopUpBoxTarget").css({"left":box_pos, "top":top_position}).slideDown(400);
    });
}

function getScrollOffset() {
  if (self.pageYOffset) return(self.pageYOffset);
  if (document.documentElement &&  document.documentElement.scrollTop) return(document.documentElement.scrollTop);
  if (document.body)return(document.body.scrollTop);
}

function assignOnResizeCoverLayerAdjustments() {
  $(document).ready(function(){
    $(window).resize(function(){popUpPositionAdjustment()});
    $(window).scroll(function(){popUpPositionAdjustment()});
  });
}

function popUpPositionAdjustment() {
  var body_width = $("body").width();
  if (body_width < 996) {body_width = 996;}
  var body_height = $(document).height();
  var central_pos = parseInt(body_width/2);
  $("#CoverLayer").css({"width":body_width, "height":body_height});
  $("div.BlackOutPopUp").css({"left":central_pos - 200, "top": getScrollOffset() + 150});
}
/******* end WARNING POPUP functions ********/


/********* ADD MORE FORM FIELDS functions *********/
//show empty, hide not empty form fields (set of fields); needed on page load  
function initFormSectionsVisibility(sh_box_class) {
  $("div." + sh_box_class).each(function() {
    if (isFormSectionEmpty(this)) {
      $(this).css('display','none');
    } else {
      $(this).css('display','block');
    };
  });
}

/* check if a set of fields in parent_ref is empty; needed on page load */
/* this function is specific to the actual form fields, more test may need to be added for different forms */
function isFormSectionEmpty(parent_ref) {  //extend the tests
  var all_inputs_in_the_section = parent_ref.getElementsByTagName('input');
  var all_selects_in_the_section = parent_ref.getElementsByTagName('select');
  //var all_textareas_in_the_section = parent_ref.getElementsByTagName('textarea');
  for (var i=0; i < all_inputs_in_the_section.length; i++) {
    if ((all_inputs_in_the_section[i].type != "checkbox") && 
        (all_inputs_in_the_section[i].type != "radio") && 
        (all_inputs_in_the_section[i].value != "") && 
        (all_inputs_in_the_section[i].value != "dd/mm/yyyy")) return false;
  }
  for (var i=0; i < all_selects_in_the_section.length; i++) {
    if (all_selects_in_the_section[i].selectedIndex != "0") return false; 
  }    
  return true;
}

//open first hidden (empty) panel
function addMoreAddresses(button_class, related_sh_box_class) {
  $("div." + related_sh_box_class + ":hidden").eq(0).slideDown(300);
  updateButtonVisibility(button_class ,related_sh_box_class);
  return false;
}

/* decide whether to hide or show the "add more" button */
function updateButtonVisibility(button_class, related_sh_box_class) {
  if ($("div." + related_sh_box_class + ":hidden").length == 0) {
    $("div." + button_class).css('display','none')
  } else {
    $("div." + button_class).css('display','block')
  }
}
/******* end ADD MORE functions ********/


/********* SELECT WITH FILTER functions *********/
//function invoked onload at body tag; or just before closiong body tag
function initArrays() {
  select_objects = document.getElementsByTagName('select'); //must be global
  all_selects = new Array();  //must be global, 3 dimensional array [ids of all selects][counter of each option in given select]['value' or 'text']= value or text of given option in given select
  options_selected = new Array(); //must be global, 2 dimensional array [ids of selects on which onchange or onkeydown function was invoked][values of selected options for associative addressing]=true ,but this boolean value is not used, existence of array entry is tested.
   
  for(var i=0; i<select_objects.length; i++) {
    var index = select_objects[i].id;  // id of select tag
    all_selects[index]= new Array();
    options_selected[index]= new Array();
    for (var j=0; j<select_objects[i].length; j++) {  //number of options elements in given select tag
      all_selects[index][j]= new Array();
      all_selects[index][j]['value'] = select_objects[i].options[j].value;
      all_selects[index][j]['text']  = select_objects[i].options[j].text;
    }//for j
  }//for i
}

//function invoked onkeyup of input tag containing search phrase
function filterFunction(container_id, filter) {
  //container_id - id of a div containing related ddl
  //filter - reference to input tag containing filter phrase or "" for bringing back all options into select
  //sel - reference to related dropdownlist (select)
  var container_ref = document.getElementById(container_id);
  var sel = container_ref.getElementsByTagName("select")[0];
  if (sel) { 
      var select_id = sel.id;
  } else {
      return; //if sendForm gives unpredictable id of other listboxes that don't use filter
  }

  if (options_selected[select_id].length == 0) 
     selectFunction(document.getElementById(select_id)); //remember already selected options, not only these selected manualy
  sel.options.length=0; 
  var k=0;
  for (var i=0; i<all_selects[select_id].length; i++) {
    var t = all_selects[select_id][i]['text'];
    var t_for_search = t.toLowerCase();
    var v = all_selects[select_id][i]['value'];
    var filter_text = (typeof filter == "object") ? filter.value.toLowerCase() : '';
    if (t_for_search.indexOf(filter_text) >= 0)  // == to search from the begining of the listbox item
       sel.options[k++] = new Option(t, v, false, (typeof options_selected[select_id][v] != "undefined"));
  }
}

//function invoked onchange at select tag, to remember the selected items
//At the moment cannot be used on autopsstback list, but maybe isn's important there, and can be omitted
function selectFunction(this_select) {
  var number_of_options = this_select.options.length;  //in given select
  for (var i=0; i<number_of_options; i++) {
    if (this_select.options[i].selected == true) {
      options_selected[this_select.id][this_select.options[i].value]=true;
    } else {
      if (typeof options_selected[this_select.id][this_select.options[i].value] != "undefined") 
          delete options_selected[this_select.id][this_select.options[i].value];
    }
  }   
}
/******* end SELECT WITH FILTER functions ********/

/******* Xstandard functions *********/
function openWysiwyg(html_source_id, html_destination_id, editor_width, editor_height, popup_left, popup_top, style_filename, content_type) {
  //content_type = "email" for emails and "page" for page contents editing
  editor_width = parseInt(editor_width) + 18; //18px for editor scrollbars
  var popup_width = parseInt(editor_width) + 20;
  var popup_height = parseInt(editor_height) + 50;

  var dynamic_url = "http://" + document.domain;
  if (document.URL.indexOf(":81/") > -1) dynamic_url += ":81";
  if (document.URL.indexOf("localhost") > -1) {
    alert("The editor shouldn't be used on localhost. It should run from the server on which the image storage folder is located ('cms-uploaded' directory).");
    dynamic_url = "http://coast.obs-group.co.uk:81"
  }

  var email_prefix = (content_type == "email") ? "email-" : "";

  var ww = window.open("", "EditorWindow", "resizable=no,width=" + popup_width + ",height= " + popup_height + ",top=" + popup_top + ",left= " + popup_left);

  ww.document.open();
  ww.document.writeln('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">\n<head>\n<title>WYSIWYG content editor</title>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />\n</head>\n<body>');
  ww.document.writeln('<div style="margin-left:auto; margin-right:auto; width:' + editor_width + 'px;">');
  ww.document.writeln('<object type="application/x-xstandard" id="editor1" width="' + editor_width + '" height="' + editor_height + '">');
  ww.document.writeln('<param name="Value" value="' + htmlEncode(document.getElementById(html_source_id).value) + '" />');

  ww.document.writeln('<param name="ImageLibraryURL"      value="' + dynamic_url + '/xstandard/' + email_prefix + 'imagelibrary.aspx" />');
  ww.document.writeln('<param name="AttachmentLibraryURL" value="' + dynamic_url + '/xstandard/' + email_prefix + 'attachmentlibrary.aspx" />');
  ww.document.writeln('<param name="LinkLibraryURL"       value="' + dynamic_url + '/xstandard/linklibrary.aspx" />');
  //ww.document.writeln('<param name="SpellCheckerURL"      value="' + dynamic_url + '/xstandard/spellchecker.aspx" />'); //http://soap.xstandard.com/spellchecker.aspx for test
  ww.document.writeln('<param name="Styles"               value="' + dynamic_url + '/xstandard/' + email_prefix + 'editor-styles.xml" />');
  ww.document.writeln('<param name="License"              value="' + dynamic_url + '/xstandard/license.txt" />');
  ww.document.writeln('<param name="CSS"                  value="' + dynamic_url + '/xstandard/' + email_prefix + style_filename + '" />');
  //ww.document.writeln('<param name="CSS"                  value="http://localhost:1153/xstandard/' + email_prefix + style_filename + '" />');

 //ww.document.writeln('<param name="SpellCheckerLangFilter" value="en-gb, en-us" />');
  ww.document.writeln('<param name="SpellCheckerLang" value="en-us" />');
  ww.document.writeln('<param name="ProxySetting" value="direct" />');
  ww.document.writeln('<param name="EnableTimestamp" value="no" />'); //the comment inserted at the begining of html
  ww.document.writeln('<param name="EnablePasteMarkup" value="no" />'); //copying from word with formating retained - doesn't work good enough
  ww.document.writeln('<param name="Lang" value="en" />');
  ww.document.writeln('<param name="Dir" value="ltr" />');
  ww.document.writeln('<param name="Debug" value="no" />');
  ww.document.writeln('<param name="Options" value="2128" />'); //hide line numbers, make images decorative by default, make divs don't disappear during edition.
  ww.document.writeln('<param name="ClassImageFloatLeft"  value="LeftImage" />');
  ww.document.writeln('<param name="ClassImageFloatRight" value="RightImage" />');
  ww.document.writeln('<param name="ToolbarWysiwyg" value="ordered-list, unordered-list, definition-list, draw-layout-table, separator, image, hyperlink, attachment, source, preview, help" />'); // spellchecker,
  ww.document.writeln('<param name="ToolbarPreview" value="wysiwyg, source, preview" />');
  ww.document.writeln('<param name="ToolbarSource" value="word-wrap, validate, wysiwyg, source, preview" />');
  ww.document.writeln('<param name="ShowStyles" value="yes" />'); //styles ddlist in the editor
  ww.document.writeln('<param name="Base" value="' + dynamic_url + '/cms-uploaded/" />'); //URL used to resolve relative URLs for images defined in markup.
  ww.document.writeln('</object>');

  ww.document.writeln('<div>\n<span style="float:right; height:16px; display:block; margin-top:10px; background-color:#003366;"><a style="font-weight:bold; font-size:10px; font-family:Verdana; text-decoration:none; color:#fff; padding:1px 8px 2px 8px; display:block;" href="javascript:self.opener.document.getElementById(\'' + html_destination_id + '\').value=document.getElementById(\'editor1\').value; self.close();" title="Update the page form and close the editor">Close</a></span>\n</div>');
  ww.document.writeln('</body>\n</html>');
  ww.document.close();
}

function htmlEncode(s) {
  var str = new String(s);
  str = str.replace(/&/g, "&amp;");
  str = str.replace(/</g, "&lt;");
  str = str.replace(/>/g, "&gt;");
  str = str.replace(/"/g, "&quot;");
  return str;
}
/******* end Xstandard functions *********/