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) ? 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');
  document.writeln("#CategoryNav ul * ul {display:none;}\n");
  document.writeln("#CategoryNav ul * li {display:none;}\n");

  if (msie_80) {
  }

  if (msie_70) {
  }
  
  if (msie_old) {
    document.writeln('.CentreColumn {height:400px;}\n');
  }
  
  if (msie_only) {
    document.writeln('.MainDiv {left:1px;}\n');
    document.writeln('.RbVerticalList {left:-6px; top:-2px;}\n');
    document.writeln('.RbVerticalList input {position:relative; top:3px}\n');
    document.writeln('.CbVerticalList {left:-6px; top:-2px;}\n');
    document.writeln('.CbVerticalList input {position:relative; top:3px}\n');
    document.writeln('.AccessCBList input {top:-4px; left:-5px; position:relative;}\n');
    document.writeln('.AccessCBList label {top:-5px; left:-5px; position:relative;}\n');
  }
  if (opera) {
    document.writeln('.Radio, .CheckBox {margin-left:3px; margin-right:2px;}\n');  
    document.writeln('.Treeview td {padding-top:2px;}\n');
    document.writeln('.RbVerticalList {left:-1px;}\n');
    document.writeln('.RbVerticalList input {margin-top:2px; margin-bottom:3px;}\n'); 
    document.writeln('.CbVerticalList {left:-1px;}\n');
    document.writeln('.CbVerticalList input {margin-top:2px; margin-bottom:3px;}\n');     
    document.writeln('.AccessCBList input {margin-right:3px;}\n');
  }
  if (firefox) {
    document.writeln('.Radio, .CheckBox {margin:4px; margin-right:3px; top:2px;}\n');
    document.writeln('.Radio2 {position:relative; top:2px;}\n');
    document.writeln('.Treeview input {margin-top:5px;}\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');    
    document.writeln('.AccessCBList input {margin-right:3px; top:2px; position:relative;}\n');
    document.writeln('.AccessCBList label {margin-right:13px;}\n');
  }
  if (safari) {
    document.writeln('.SearchBar .CategorySelect {font-size:1.1em;}\n');
    document.writeln('#CategoryNav a {padding-top:6px;}\n');
    document.writeln('.Radio, .CheckBox {margin:4px; top:0px;}\n');
    document.writeln('.Treeview input {margin-top:7px;}\n');
    document.writeln('.RbVerticalList input {margin-top:4px; margin-bottom:3px;}\n');    
    document.writeln('.RbVerticalList label {margin-left:7px;}\n');
    document.writeln('.CbVerticalList input {margin-top:4px; margin-bottom:3px;}\n');    
    document.writeln('.CbVerticalList label {margin-left:7px;}\n');    
    document.writeln('.AccessCBList input {margin-right:3px;}\n');
  }
  if (chrome) {
    document.writeln('.RbVerticalList input {margin-top:4px; margin-bottom:3px;}\n');    
    document.writeln('.RbVerticalList label {position:relative; top:-2px; margin-left:7px;}\n');
    document.writeln('.CbVerticalList input {margin-top:4px; margin-bottom:3px;}\n');    
    document.writeln('.CbVerticalList label {position:relative; top:-2px; margin-left:7px;}\n');
  }
document.writeln('/*]]>*/\n</style>\n');

function placeFlash(path, width, height, quality, loop) {
  var RandomNumber = Math.ceil(Math.random()*100000);
  var ObjectId = "eiuoa" + RandomNumber;
  var FlashObjectCode;

  FlashObjectCode = '<object id="' + ObjectId + '"  width="' + width + '" height="' + height + '" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0">\n';
  FlashObjectCode+= '<param name="quality" value="' + quality + '" />\n';
  FlashObjectCode+= '<param name="loop" value="' + loop + '" />\n';
  FlashObjectCode+= '<param name="wmode" value="opaque" />\n';
  FlashObjectCode+= '<param name="allowScriptAccess" value="sameDomain" />\n';
  FlashObjectCode+= '<embed src="' + path + '" quality="' + quality + '" width="' + width + '" height="' + height + '" menu="false" allowscriptaccess="sameDomain" wmode="opaque" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"></embed>\n';
  FlashObjectCode+= '</object>\n';
  document.write(FlashObjectCode);
  document.getElementById(ObjectId).movie=path;
  //alert(FlashObjectCode);
}

function clearField (field_to_clear, initial_value) {
  if (initial_value == field_to_clear.value) field_to_clear.value="";
} 

function fillField (field_to_clear, initial_value) {
  if (field_to_clear.value == "") field_to_clear.value=initial_value;
}

//information box on validation image rollover
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";
}

//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="Maximum text length is "+ max_length +" characters.";
  }
  if ((actual_length > 0)&&(actual_length <= max_length)) {
    document.getElementById(info).innerHTML="You may enter "+ characters_left +" more characters.";
  }
  if (actual_length > max_length) {
    element.value = element.value.substr(0, max_length);
    document.getElementById(info).innerHTML="You may enter "+ characters_left +" more characters.";
  }
}

//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);
  }
}

//for search panel
function clearSearchField (field_to_clear) {
  var tmp_obj = field_to_clear.previousSibling;
  tmp_obj=tmp_obj.previousSibling;
  var initial_value = tmp_obj.value;
  if (initial_value == field_to_clear.value) field_to_clear.value="";
} 

//for search panel
function fillSearchField (field_to_fill) {
  var tmp_obj = field_to_fill.previousSibling;
  tmp_obj=tmp_obj.previousSibling;
  var initial_value = tmp_obj.value;
  if (field_to_fill.value == "") field_to_fill.value=initial_value;
}

function __printPage(strUrl) {
  var newWindow = window.open(strUrl,"Print", "toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=yes,copyhistory=no,width=800,height=700");
}
	
function __popupPage(strUrl) {
  var newWindow = window.open(strUrl,"PopUp", "toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=yes,copyhistory=no,width=916,height=600,top=200,left=200");
}


/* Category navigation */
var previous_this; //global
var selection_cache_1;

$(document).ready(function(){

  //Initialization - hide all, add special classes
  $("#CategoryNav > ul").addClass("Main");
  $("#CategoryNav > ul > li").addClass("Main");
  $("#CategoryNav li.Main > a").addClass("MainCatBg");

  $("#CategoryNav li.Main li:has(ul)").each(function() {
    $(this).children("a").addClass("HasChildren");
  });

  //Initialization - open selected category on page load
  var index_of_menu_container = $("#CategoryNav a.Selected").parents().index( $("#CategoryNav") );
  $("#CategoryNav a.Selected").parents().slice(0, index_of_menu_container).each(function() { 
    if ( $(this).children().length > 1 ) {
      $(this).children().filter("a").addClass("BreadCrumb"); //add BreadCrumb to all parents in a chain, but not to selected option without children
    }
  });

  selection_cache_1 = $("#CategoryNav a.Selected");
  selection_cache_1.parents().slice(0, index_of_menu_container).show();
  selection_cache_1.parent().find("ul:first > li > a").addClass("Leaf"); //add Leaf to childeren options if there were any
  selection_cache_1.parent().find("ul:first > li:last-child > a").addClass("LastLeaf"); //add LastLeaf to childeren options if there were any
  //no CurrentlyDisplayed assigned here because selected was a node with children so CurrentlyDisplayed category is undefined
  selection_cache_1.parent().find("ul:first > li").show(); //show childeren <li> of child <ul> if there were any
  selection_cache_1.parent().children().show(); //show child <a> and <ul> if there were any
  
  if (selection_cache_1.parent().children().length == 1) { //if no child ul, show siblings
    selection_cache_1.parent().parent().not(".Main").find("li > a").addClass("Leaf"); //add leaf to selected and its siblings (but not to Main options). There are no children to open
    selection_cache_1.parent().parent().find("li:last-child > a").addClass("LastLeaf"); //add LastLeaf to last child about to open
    selection_cache_1.parent().parent().not(".Main").find("li > a.Selected").addClass("CurrentlyDisplayed");
    //selection_cache_1.parent().parent().not(".Main").find("li > a.Selected").addClass("CurrentlyDisplayed"); //version that assigns class also to main categories. Is 'not(".Main")' needs to be there?
    selection_cache_1.parent().siblings().show();
    selection_cache_1.removeClass("Selected");
  }

  //on click actions
  $("#CategoryNav a").click(function(){
    previous_this = $(this);
    
    if ((previous_this.attr("href") != "#") && (previous_this.hasClass("BreadCrumb") == false)) return true; //if a link not on breadcrumb - skip animation, just follow the link
  
    var was_selected = $(this).hasClass("Selected");
          
    $(this).parent().filter(".Main").siblings().find("ul").slideUp(); //maybe not needed on click of main option

    var number_of_children = $(this).parent().children().length;   
     
    if ((number_of_children > 1 ) && (!was_selected))  {//if clicked has children and was not selected
      $("#CategoryNav a.Selected").removeClass("Selected"); //don't use selection_cache_1 here
      $(this).addClass("Selected");

      $(this).parent().parent().not(".Main").slideUp(500, function() //side up ul that contains li that contains clicked a, but not top level
      {
        previous_this.parent().siblings().hide();  //hiding for sub level, hide siblings li's
        previous_this.parent().find("ul").hide();  //hide all child ul's
        openCallback1();
      });

      if ($(this).parent().parent().filter(".Main").length == 1 ) { //slideUp for Main category (top level)
        previous_this.parent().find("ul").slideUp(500); //slide up all child ul, some of them are hidden so callback here would fire instantly, and of course will fire many times
        //no hiding all child li's - looks like works ok without. if not use delayed hiding not callback in above line
        previous_this.parent().siblings().children().filter("a").removeClass("BreadCrumb"); //remove BreadCrumb if opening another main category (with suboptions)
        openCallback2();
      } 
    }
 
    if (number_of_children == 1) { //clicked has no children
      $("#CategoryNav a.CurrentlyDisplayed").removeClass("CurrentlyDisplayed");
      previous_this.parent().not(".Main").children().filter("a").addClass("CurrentlyDisplayed");
      //previous_this.parent().children().filter("a").addClass("CurrentlyDisplayed"); //version that assigns class also to main categories
      if ($(this).parent().filter(".Main").length == 1) { //clicked is main category option
        $("#CategoryNav > ul.Main > li.Main > a.Selected").removeClass("Selected");     //remove Selected if all main categories are closed and if there is no child ul to open.
        $("#CategoryNav > ul.Main > li.Main > a.BreadCrumb").removeClass("BreadCrumb"); //remove BreadCrumb if all main categories are closed and if there is no child ul to open.
      }
    }
 
    if (previous_this.hasClass("BreadCrumb")) return false;   //if link or # on breadcrumb - don't follow the link
     
  }); //onclick
  
}); //ready        

function openCallback1() {
  previous_this.addClass("BreadCrumb");
  var id_Ti = window.setTimeout("openCallback()",1); //delay not needed because callback is used for sub option click
}

function openCallback2() {
  previous_this.addClass("BreadCrumb");
  var id_Ti = window.setTimeout("openCallback()",300); //delay needed because no callback is used for main option click
}

function openCallback() {
  previous_this.parent().find("ul > li").show();
  previous_this.parent().find("a.Leaf").removeClass("Leaf"); //remove any Leaf
  previous_this.parent().find("a.LastLeaf").removeClass("LastLeaf"); //remove any LastLeaf
  previous_this.parent().find("ul > li > a").removeClass("BreadCrumb"); //remove BreadCrumb from children about to open
  previous_this.parent().find("ul > li > a").addClass("Leaf"); //add leaf to children about to open
  previous_this.parent().find("ul > li:last-child > a").addClass("LastLeaf"); //add LastLeaf to last child about to open
  
  previous_this.parent().parent().slideDown(300, function() //open clicked ul with hidden earlier siblings li's
  {
    previous_this.parent().children().filter("ul").slideDown(); //open child ul with opened earlier li's
  });
}
/* Category navigation - end*/

function openWysiwyg(html_source_id, html_destination_id, editor_width, editor_height, popup_width, popup_height, popup_left, popup_top) {
  
  var dynamic_url = "http://" + document.domain;
  if (document.URL.indexOf(":81/") > -1) dynamic_url += ":81";
  if (document.URL.indexOf("localhost") > -1) dynamic_url = "http://westminsterinternational.obs-group.co.uk:81"

  var ww = window.open("", "EditorWindow", "resizable=no,width=" + popup_width + ",height= " + popup_height + ",top=" + popup_top + ",left= " + popup_left);
    
  //alert(htmlEncode(document.getElementById(html_source_id).value));
  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>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/imagelibrary.aspx" />');
  ww.document.writeln('<param name="AttachmentLibraryURL" value="' + dynamic_url + '/xstandard/attachmentlibrary.aspx" />');
  ww.document.writeln('<param name="LinkLibraryURL"       value="' + dynamic_url + '/xstandard/linklibrary.aspx" />');
  ww.document.writeln('<param name="Styles"               value="' + dynamic_url + '/xstandard/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/general.css" />');

  ww.document.writeln('<param name="ProxySetting" value="direct" />'); //if default proxy settings stop it from working
	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="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, draw-data-table, separator, image, hyperlink, attachment, source, preview, help" />');
  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="no" />'); //styles ddlist in the editor
  ww.document.writeln('<param name="Base" value="'+ dynamic_url +'/cms-uploaded/" />');
  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="Save and Close">Save and 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;
}


//MAP FUNCTIONALITY
var keep_selected_image_id = ""; //global variable

//keep_selected_image_id is case sensitive
function keepHighlightedElement() {
  var keep_selected_country_code;
  if (document.URL.indexOf("countryCode=") != -1) {
    keep_selected_country_code = document.URL.substring(document.URL.indexOf("countryCode=") + 12, document.URL.indexOf("countryCode=") + 15);
    keep_selected_image_id = $("#WorldMap").find("area[href*=" + keep_selected_country_code + "]").get(0).title;
    keep_selected_image_id = "Country" + keep_selected_image_id.replace(/ +/g,"");
    document.getElementById(keep_selected_image_id).style.display = 'block';
  }
}

function mapRollIn(overlay_name, display_name) {
  if (document.getElementById(overlay_name)) document.getElementById(overlay_name).style.display = 'block';
  $("#BarBelowMap div.Right").html(display_name);
}

//uses global variable - keep_selected_image_id
function mapRollOut() {
  if (keep_selected_image_id.length > 0) {
    $("#LayerOverlayContainer img").not("#" + keep_selected_image_id).hide();
  } else {
    $("#LayerOverlayContainer img").hide();
  }
  $("#BarBelowMap div.Right").html("");
}

/* uses hidOffice and hidAgent input fields for points coordinates, and add_hardcoded_stars (if on the page)*/
function placePoints() {
  var dots_array = new Array();
  var stars_array = new Array();
  var hardcoded_stars_array = new Array();
  var layer_contents = "";
  var new_element = "";
  
  $(document).ready(function(){
    stars_array = document.getElementById("PointsCoordinates").getElementsByTagName("input")[0].value.split(",");  
    dots_array  = document.getElementById("PointsCoordinates").getElementsByTagName("input")[1].value.split(",");
     
    if (stars_array.length > 1) { //Offices
      for (var i=0; i<stars_array.length; i=i+2) {
        new_element = document.createElement("div");
        new_element.className = "Star";
        new_element.style.left = stars_array[i] + "px";
        new_element.style.top  = stars_array[i+1] + "px";
        document.getElementById("LayerPoints").appendChild(new_element);
      }
    }

    if (dots_array.length > 1) { //Agents
      for (var i=0; i<dots_array.length; i=i+2) {
        new_element = document.createElement("div");
        new_element.className = "Dot";
        new_element.style.left = dots_array[i] + "px";
        new_element.style.top  = dots_array[i+1] + "px";
        document.getElementById("LayerPoints").appendChild(new_element);
      }
    }
    
    if (typeof add_hardcoded_stars != "undefined") {
      hardcoded_stars_array = add_hardcoded_stars.split(",");
      if (hardcoded_stars_array.length > 1) { //Offices
        for (var i=0; i<hardcoded_stars_array.length; i=i+2) {
          new_element = document.createElement("div");
          new_element.className = "Star";
          new_element.style.left = hardcoded_stars_array[i] + "px";
          new_element.style.top  = hardcoded_stars_array[i+1] + "px";
          document.getElementById("LayerPoints").appendChild(new_element);
        }
      }
    }
  }); //ready
}

function AdminRegionSwitch(ddlist_ref) {
  var new_class_name;
  var text_selected = ddlist_ref.options[ddlist_ref.selectedIndex].text;

  if (text_selected == "Africa")        new_class_name = "BackgroundAfrica";
  if (text_selected == "Asia")          new_class_name = "BackgroundAsia";
  if (text_selected == "Europe")        new_class_name = "BackgroundEurope";
  if (text_selected == "Middle East")   new_class_name = "BackgroundMiddleEast";
  if (text_selected == "North America") new_class_name = "BackgroundNorthAmerica";
  if (text_selected == "Oceania")       new_class_name = "BackgroundOceania";
  if (text_selected == "South America") new_class_name = "BackgroundSouthAmerica";

  if(msie_old) {//animation in IE6 looks bad
    $("#ForJSRegionsMap div:eq(2)").removeClass().addClass(new_class_name);
  } else {
    $("#ForJSRegionsMap div:eq(2)").fadeOut(250, function () {
      $(this).removeClass().addClass(new_class_name).fadeIn(250);
    });
  }
}

function initAdminRegion(ddlist_ref) {
  var new_class_name;
  var text_selected = ddlist_ref.options[ddlist_ref.selectedIndex].text;

  if (text_selected == "Africa")        new_class_name = "BackgroundAfrica";
  if (text_selected == "Asia")          new_class_name = "BackgroundAsia";
  if (text_selected == "Europe")        new_class_name = "BackgroundEurope";
  if (text_selected == "Middle East")   new_class_name = "BackgroundMiddleEast";
  if (text_selected == "North America") new_class_name = "BackgroundNorthAmerica";
  if (text_selected == "Oceania")       new_class_name = "BackgroundOceania";
  if (text_selected == "South America") new_class_name = "BackgroundSouthAmerica";

  $("#ForJSRegionsMap div:eq(2)").removeClass().addClass(new_class_name);
}

function getAbsolutePosition(element) {
  var r = { x: element.offsetLeft, y: element.offsetTop };
  if (element.offsetParent) {
    var tmp = getAbsolutePosition(element.offsetParent);
    r.x += tmp.x;
    r.y += tmp.y;
  }
  return r;
};

function getRelativeCoordinates(event, reference) {
  var x, y;
  event = event || window.event;
  var el = event.target || event.srcElement;

  if (!window.opera && typeof event.offsetX != 'undefined') {
    var pos = { x: event.offsetX, y: event.offsetY };

    var e = el;
    while (e) {
      e.mouseX = pos.x;
      e.mouseY = pos.y;
      pos.x += e.offsetLeft;
      pos.y += e.offsetTop;
      e = e.offsetParent;
    }

    var e = reference;
    var offset = { x: 0, y: 0 }
    while (e) {
      if (typeof e.mouseX != 'undefined') {
        x = e.mouseX - offset.x;
        y = e.mouseY - offset.y;
        break;
      }
      offset.x += e.offsetLeft;
      offset.y += e.offsetTop;
      e = e.offsetParent;
    }

    e = el;
    while (e) {
      e.mouseX = undefined;
      e.mouseY = undefined;
      e = e.offsetParent;
    }
  } else {
    var pos = getAbsolutePosition(reference);
    x = event.pageX  - pos.x;
    y = event.pageY - pos.y;
  }

  return { x: x, y: y };
}

//update markers position on map click
function ReadXY(event, coordinates_reference_id, marker_id, form_field_x_ref, form_field_y_ref) {
  var e = event || window.event;
  var pos = getRelativeCoordinates(event, document.getElementById(coordinates_reference_id));
  var marker_ref = document.getElementById(marker_id);
  marker_ref.style.left = pos.x +'px';
  marker_ref.style.top  = pos.y +'px';
  form_field_x_ref.value = pos.x;
  form_field_y_ref.value = pos.y;
  //document.getElementById('output').innerHTML = "pos.x= " + pos.x + " pos.y="+pos.y; //deb
}

//sets initial position of the markers on edit and view pages
//hidden fields may be empty; markers may not exist
function initMarkersPosition() {
  var hid_world_grid_x_ref = document.getElementById('ForJSHiddenCoordinates').getElementsByTagName('input')[0];
  var hid_world_grid_y_ref = document.getElementById('ForJSHiddenCoordinates').getElementsByTagName('input')[1];
  var hid_continent_grid_x_ref = document.getElementById('ForJSHiddenCoordinates').getElementsByTagName('input')[2];
  var hid_continent_grid_y_ref = document.getElementById('ForJSHiddenCoordinates').getElementsByTagName('input')[3];
  var world_marker_ref = document.getElementById('Marker1');
  var region_marker_ref = document.getElementById('Marker2');;
  
  //world marker position
  if (world_marker_ref) {
    if ((parseInt(hid_world_grid_x_ref.value) != "NaN") && (parseInt(hid_world_grid_y_ref.value) != "NaN")) {
      world_marker_ref.style.left = parseInt(hid_world_grid_x_ref.value) + "px";
      world_marker_ref.style.top  = parseInt(hid_world_grid_y_ref.value) + "px";
    }
  }

  //region marker position
  if (region_marker_ref) {
    if ((parseInt(hid_continent_grid_x_ref.value) != "NaN") && (parseInt(hid_continent_grid_y_ref.value) != "NaN")) {
      region_marker_ref.style.left = parseInt(hid_continent_grid_x_ref.value) + "px";
      region_marker_ref.style.top  = parseInt(hid_continent_grid_y_ref.value) + "px";
    }
  }
}

//on admin edit page, invoked on office radio button change, markers may not exist
function updateMarkerType(indication_inside_id) {
  var world_marker_ref = document.getElementById('Marker1');
  var region_marker_ref = document.getElementById('Marker2');

  if (indication_inside_id == "ForJSTypeCheckRadio") {
    var office_yes_radio_ref = document.getElementById(indication_inside_id).getElementsByTagName("input")[0];
    if (office_yes_radio_ref.checked) {
      if (region_marker_ref != 'undefined') $(region_marker_ref).removeClass().addClass("Star");
      if (world_marker_ref != 'undefined')  $(world_marker_ref).removeClass().addClass("Star");
    } else {
      if (region_marker_ref != 'undefined') $(region_marker_ref).removeClass().addClass("Dot");
      if (world_marker_ref != 'undefined')  $(world_marker_ref).removeClass().addClass("Dot");
    }
  }
  
  if (indication_inside_id == "ForJSTypeCheckViewPage") {
    var office_span_ref = document.getElementById(indication_inside_id).getElementsByTagName("span")[0];
    
    if (office_span_ref.innerHTML.indexOf("Yes") > -1) {
      if (region_marker_ref != 'undefined') $(region_marker_ref).removeClass().addClass("Star");
      if (world_marker_ref != 'undefined')  $(world_marker_ref).removeClass().addClass("Star");
    } else {
      if (region_marker_ref != 'undefined') $(region_marker_ref).removeClass().addClass("Dot");
      if (world_marker_ref != 'undefined')  $(world_marker_ref).removeClass().addClass("Dot");
    }
  }
}


//change the approptiate style atributes by JS right afrter the tabs are creted on the page
function initTabs() {
  var category_indicator_ref = document.getElementById("ForJsCategoryIndicator").getElementsByTagName("input")[0];
  
  switch (category_indicator_ref.value) {
    case "Fire":
      document.getElementById("TabBackingFire").style.top = "139px";
      document.getElementById("TabBackingFire").style.height = "23px";
      document.getElementById("TabImageFire").style.height = "139px";
    break;
    case "Safety":
      document.getElementById("TabBackingSafety").style.top = "139px";
      document.getElementById("TabBackingSafety").style.height = "23px";
      document.getElementById("TabImageSafety").style.height = "139px";
    break;
    case "Security":
      document.getElementById("TabBackingSecurity").style.top = "139px";
      document.getElementById("TabBackingSecurity").style.height = "23px";
      document.getElementById("TabImageSecurity").style.height = "139px";
    break;    
    case "Defence":
      document.getElementById("TabBackingDefence").style.top = "139px";
      document.getElementById("TabBackingDefence").style.height = "23px";
      document.getElementById("TabImageDefence").style.height = "139px";
    break;
  }
}


//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)
       sel.options[k++] = new Option(t, v, false, (typeof options_selected[select_id][v] != "undefined"));
  }
}

//function invoked onchange at select tag
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];
    }
  }   
}

function __printPage(strUrl) {
  var newWindow = window.open(strUrl,"Print", "toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=yes,copyhistory=no,width=650,height=700");
}
	
function __popupPage(strUrl) {
  var newWindow = window.open(strUrl,"PopUp", "toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=yes,copyhistory=no,width=916,height=600,top=200,left=200");
}

function SelectRadio(){
  if (document.getElementById("ForJSRadioList")) { 
    var radio_number = document.getElementById("ForJSRadioList").getElementsByTagName("input").length;
    if (radio_number > 0) {
      var last_radio = radio_number - 1;
      document.getElementById("ForJSRadioList").getElementsByTagName("input")[last_radio].checked="true";
    }
  }
}

//Assign default on press enter button (input inside button_id) to form fields inside form_id
function assignDefaultButton(evt, button_id) {
  var button_ref = document.getElementById(button_id).getElementsByTagName('input')[0];
  var keyCode = evt.keyCode;

  if(keyCode == 13) {
    button_ref.click();
    return false;
  }
  return true;
}

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;
}


function initSitemap(){

  $('.Sitemap2 .Section').each(function(){
    
    
                
    if($(this).find('span:not(a span)').length == 0){
      $(this).find('a').css('padding-left','0px') 
    }
    $(this).find('span:first').css('padding-left','0px')
  
  });

}



$(document).ready(function(){

  $(".LeftQuotationMarks").css({opacity: "0.3"}); 
  $(".RightQuotationMarks").css({opacity: "0.3"}); 
   
  $(".TransparentBG").css({opacity: "0.5"}); 
  
  $("#LoginButton").click(function(){
    $(".LoginInfo").slideUp(200);
    if ( $(".LoginBoxInner").is(':hidden') ) {
      $(".LoginBoxInner").show(600);
    } else {
      $(".LoginBoxInner").slideUp(300);
    }
  });
  
  //Fire, Safety, Security, Defence - tabs animations
  $("a.ImageTabLink").hover(
    function(){ //onmouseover function
      $(this).next("div").stop().animate({height: "139"}, 250);
      $(this).prev("div").stop().animate({height: "23", top: "139"}, 250);
    },  
    function(){ //onmouseout function
      var category_indicator_ref = document.getElementById("ForJsCategoryIndicator").getElementsByTagName("input")[0];
      var selected_category_name = category_indicator_ref.value;
      var current_category_name = $(this).attr("title");
      
      if (selected_category_name != current_category_name) {
        $(this).next("div").stop().animate({height: "0"}, 250);
        $(this).prev("div").stop().animate({height: "2", top: "161"}, 200);
      }
  }); 
  
  $("a.ImageTabLink2").hover(
    function(){ //onmouseover function
      $(this).next("div").stop().animate({height: "139"}, 250);
      $(this).prev("div").stop().animate({height: "23", top: "139"}, 250);
    },  
    function(){ //onmouseout function      
        $(this).next("div").stop().animate({height: "0"}, 250);
        $(this).prev("div").stop().animate({height: "2", top: "161"}, 200);
  }); 
   
  $(".CloseLogIn").click(
    function() { $(".LoginBoxInner").slideUp(300);
  });

  $(".WhatsThis").hover(
    function(){
      $(this).next("div").fadeIn(200);
    },  
    function(){
      $(this).next("div").fadeOut(100);
  });
  
  if (document.getElementById('ForJSFormForButton1') && (document.getElementById('ForJSDefaultButton1'))) {
    var form1_ref = document.getElementById('ForJSFormForButton1');
    var form1_input_refs_array = form1_ref.getElementsByTagName('input');
    
    for (var i=0; i<form1_input_refs_array.length; i++) {
      if (firefox) {
        form1_input_refs_array[i].onkeypress = function(event) {return assignDefaultButton(event, 'ForJSDefaultButton1'); };
      } else {
        form1_input_refs_array[i].onkeypress = function()      {return assignDefaultButton(event, 'ForJSDefaultButton1'); };
      }
    }
  }


  if($('.CloneButton').is(':visible')){
    $('.FooterMain .ButtonStd0').clone().appendTo('.CloneButton')
    $('.FooterMain .ButtonStd0').remove()
  }
  $('.FooterMain .ButtonStd0').css('display','block')
  
  if($('.CloneButton2').length == 1){
   $('.CloneButton2').addClass('RemoveMe')
   $('.CloneButton2').clone().prependTo('.FooterMain')
   $('.RemoveMe:not(.FooterMain .RemoveMe)').remove()
   $('.CloneButton2').css('display','block') 
  };


}); //ready

