/**
* Author : Siavash Etemadieh
* Build : 50
*/

function gE(el) {return document.getElementById(el);}
function gT(el,tag) {return el.getElementsByTagName(tag);}
function hide(el) {el.style.display ="none"; }
function show(el,display) {el.style.display = display;}
function isHidden(el){ return el.style.display == "none";}
function setVisible(el,visible){ (visible)?el.style.visibility="visible":el.style.visibility="hidden";}
/*
 Written by Jonathan Snook, http://www.snook.ca/jonathan
 Add-ons by Robert Nyman, http://www.robertnyman.com
*/

function gEC(oElm, strTagName, strClassName){
 var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
 var arrReturnElements = new Array();
 strClassName = strClassName.replace(/-/g, "\-");
 var oRegExp = new RegExp("(^|\s)" + strClassName + "(\s|$)");
 var oElement;
 for(var i in arrElements){
  oElement = arrElements[i];
  if(oRegExp.test(oElement.className)){
   arrReturnElements.push(oElement);
  }
 }
 return (arrReturnElements)
}

function addLoadEvent(func) {
 var oldonload = window.onload;
 if (typeof window.onload != 'function') {
  window.onload = func;
 } else {
  window.onload = function() {
    if (oldonload) {
      oldonload();
    }
    func();
  }
 }
}

function editClass(a,o,c1,c2) {
  switch (a){
  case 'swap':
    o.className=!editClass('check',o,c1)?o.className.replace(c2,c1):o.className.replace(c1,c2);
  break;
  case 'add':
    if(!editClass('check',o,c1)){o.className+=o.className?' '+c1:c1;}
  break;
  case 'remove':
    if(editClass('check',o,c1)){
      var rep=o.className.match(' '+c1)?' '+c1:c1;
      o.className=o.className.replace(rep,'');
    }
  break;
  case 'check':
    return new RegExp('\\b'+c1+'\\b').test(o.className)
  break;
  }
}

function TabPanel(element) {
  this.tabs = gEC(element,"li","tab");
  this.tabContents = gEC(element,"div","tabContent");
}

TabPanel.prototype.init = function() {
  for(i in this.tabs) {
    this.tabs[i].onclick = function(instance) {
     return function () {
      instance.showTab(this);
     }
    }(this);
  }
  this.showTab(0);
}

TabPanel.prototype.showTab =function(tab) {
  for(var i in this.tabs) {
    var compare;
    (typeof(tab)=="number")? compare = i:compare = this.tabs[i];
    if(compare == tab) {
     show(this.tabContents[i],"block");
     editClass("add",this.tabs[i],"active-tab");
    } else {
     hide( this.tabContents[i]);;
     editClass("remove",this.tabs[i],"active-tab");     
    }   
  }
}
  
  

  
function addFocus(someArray){
  for(var i in someArray){
    someArray[i].onfocus = function() { editClass("add",this,"focus");  editClass("add",this.parentNode,"focus");}
    someArray[i].onblur = function() { editClass("remove",this,"focus");  editClass("remove",this.parentNode,"focus");}
  }
}



function Validation(warning){
 this.formArray = new Array();
 if(gE(warning)) {
  this.warning = gE(warning);
 }
}
Validation.prototype.registerInput = function(id) {
  if(gE(id)){
    this.formArray.push(gE(id));
  }
}


Validation.prototype.validateInputs = function () {
  var submit = new Boolean();
  for(var i =0;i<this.formArray.length; i++) {
    if(((this.formArray[i].tagName == "INPUT" ||this.formArray[i].tagName == "TEXTAREA") && (this.formArray[i].value.trim().length == 0)||(this.formArray[i].value.trim()=='<br>')) ||
       (this.formArray[i].tagName == "SELECT" && this.formArray[i].value == '')) {
      editClass("add",gE("row"+this.formArray[i].id),"validation");
      submit = false;
    } else {
     editClass("remove",gE("row"+this.formArray[i].id),"validation");
    }
  }
  if(this.warning){
   if(!submit) {
    this.warning.style.display="block";
   } else {
    this.warning.style.display="none";
   }
  }
  return submit;
}


String.prototype.get = function() {
 t=unescape(this);
 key=arguments[0];
 a=t.lastIndexOf(key+"=")+(key.length+1);
 if(a.length-(key.length+1)==-1) {
  return -1
 }
 b=t.substr(a);
 c=b.indexOf("&");
 if(c<0) {
  return b
 } else {
  d=b.substring(0,c);return d
 }
}
function getURLValue(varname)
{
  // First, we load the URL into a variable
  var url = window.location.href;

  // Next, split the url by the ?
  var qparts = url.split("?");

  // Check that there is a querystring, return "" if not
  if (qparts.length == 0 || url.indexOf("?")== -1)
  {
    return "";
  }

  // Then find the querystring, everything after the ?
  var query = qparts[1];

  // Split the query string into variables (separates by &s)

  var vars = query.split("&");

  // Initialize the value with "" as default
  var value = "";

  // Iterate through vars, checking each one for varname
  for (i=0;i<vars.length;i++)
  {
    // Split the variable by =, which splits name and value
    var parts = vars[i].split("=");
    
    // Check if the correct variable
    if (parts[0] == varname)
    {
      // Load value into variable
      value = parts[1];

      // End the loop
      break;
    }
  }
  
  // Convert escape code
  value = unescape(value);

  // Convert "+"s to " "s
  value.replace(/\+/g," ");

  // Return the value
  return value;
}


String.prototype.trim = function() {
 // skip leading and trailing whitespace
 // and return everything in between
  var x=this;
  x=x.replace(/^\s*(.*)/, "$1");
  x=x.replace(/(.*?)\s*$/, "$1");
  return x;
}
String.prototype.replaceAll=function() {
  return this.split(arguments[0]).join(arguments[1])
}

/* This script and many more are available free online at
The JavaScript Source!! http://javascript.internet.com
Created by: Ultimater | http://webdeveloper.com/forum/member.php?u=30185 */
function html_entity_decode(str) {
  var ta=document.createElement("textarea");
  ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
  return ta.value;
}


function addNavClass() {
  var primaryNavLis = document.getElementById("primary-navigation").getElementsByTagName("li");

  for( var i = 0; i<primaryNavLis.length;i++){
    if(primaryNavLis[i].className.indexOf("current_page") != -1 ||
       primaryNavLis[i].className.indexOf("current_page_ancestor") !=-1)
    {
       if(editClass) {
          editClass("add",primaryNavLis[i],"active_"+(i+1));
       }
    }
  primaryNavLis[i].onmouseover = function() {
   if(editClass) {
      editClass("add",this,"hover");
    }
  }
  primaryNavLis[i].onmouseout= function() {
    if(editClass) {
      editClass("remove",this,"hover");
    }
  }

  }
}

      function fontSizeToggle(){
       if(document.getElementById("block_1") && document.getElementById("block_2") && document.getElementById("fontToggle")) {
          if(document.getElementById("block_1").className =="bigger") {
            document.getElementById("fontToggle").innerHTML = "A+"
            document.getElementById("block_1").className ="";
            document.getElementById("block_2").className ="";
          } else {
            document.getElementById("fontToggle").innerHTML = "A-"
            document.getElementById("block_1").className ="bigger";
            document.getElementById("block_2").className ="bigger";
          }
        }
      }


function IdSwitcher(elId,count,delay) {
   this.element = document.getElementById(elId);
   this.delay = delay;
   this.timeout;
   this.count = count;
   this.idPrefix = "slbox-";
};

IdSwitcher.prototype = {

   start : function () {
      var that = this;
      this.stop();
      this.timeout = setInterval(function () {that.switchId();}, this.delay);
   },
   
   stop: function () {
      if(this.timeout) {
        window.clearTimeout(this.timeout);
      }
   }, 
   
   switchId : function () {
      var ran_number=Math.floor(Math.random()*this.count) +1;
      this.element.setAttribute("id", this.idPrefix + ran_number);
   }
};


/********************************************************************************* 
*This allows an alphabatised select box to be searched via an input box         **
*Implement with something like this:                                            **
*window.onload = function () {                                                  **
*   var userSelect = new SelectAutoSearch("text_box","select-box");         **
*}                                                                              **
**********************************************************************************/
// Trim leading whitespace
String.prototype.trimWS = function() { return this.replace(/^\s+|\s+$/g, ''); };
// Some names have extra spaces between first and last. This forces it to be one
String.prototype.trimMid = function() {
return this.replace(/\s+/, ''); };

 SelectAutoSearch = function (textBoxId, selectBoxId) {

    this.currentString ="";
    this.textBox = document.getElementById(textBoxId);
    this.selectBox = document.getElementById(selectBoxId).options;
    this.textBox.onkeyup = function(instance) {
        return function (evt) {
            instance.search(evt);
        }
    }(this);
 };

 SelectAutoSearch.prototype = {

    search: function(evt) {
      var key = (evt) ? evt.which : event.keyCode;
      this.currentString = this.textBox.value;
      this.selectBox.selectedIndex = this.getIndex();
    },
    // Binary Search
    getIndex: function () {
      var left = -1;
      var right = this.selectBox.length;
      var mid ;
      while(right-left > 1) {
        mid = (left + right) >>> 1;
        if(this.compare(this.selectBox[mid].innerHTML.trimWS().toLowerCase().split("\n").join("").trimMid(), this.currentString.trimMid().toLowerCase() ) == 1) {
          left = mid;
        }
        else {
          right = mid;;
        }
      }
      if( this.compare(this.selectBox[right].innerHTML.trimWS().toLowerCase().split("\n").join("").trimMid(), this.currentString.trimMid().toLowerCase()) == 0) {
        return right;
      }
        return right;
      },
      compare : function(longStr, str) {
        //var longStr = longStr.substring(0,str.length );
        if(str > longStr) {
          return 1;
        }
        else if(longStr > str) {
          return -1;
        }
        return 0;
      }
 };







DebugConsole = {
    console :null,
    evalConsole: null,
    runButton: null,
    wrapper : null,
    doubleclick : 0,
    appended : false,
    init : function() {
        this.console = document.createElement("textarea");
        this.console.className="debugConsole";
        this.evalConsole = document.createElement("textarea");
        this.evalConsole.className = "debugConsole";
        this.runButton = document.createElement("input");
        this.runButton.setAttribute("type","button");
        this.runButton.value = "Run";
        this.wrapper = document.getElementById("wrapperbot");
        this.addEventHandler();
    },
    
    show : function() {
        if(this.wrapper && !this.appended) {
            this.wrapper.appendChild(this.console);
            this.wrapper.appendChild(this.evalConsole);
            this.wrapper.appendChild(this.runButton);
            this.appended= true;
        }
        this.console.style.display ="block";
        this.evalConsole.style.display ="block";
        this.runButton.style.display ="block";
    },
    
    hide : function() {
        this.DebugConsole.style.display = "none";
        this.evalConsole.style.display ="none";
        this.runButton.style.display ="none";
    },
    log : function (message) {
        if(message && this.appended) {
            this.console.value += this.console.value = "\n"+message;
            this.console.scrollTop = this.console.scrollHeight;
        }
    },
    
    evaluate : function () {
        if(DebugConsole.appended) {
            eval(DebugConsole.evalConsole.value);
        }
    },
    addEventHandler : function() {
        if(this.wrapper) {
            this.wrapper.ondblclick = function() {
                DebugConsole.doubleclick++;
                if(DebugConsole.doubleclick > 1) {
                    DebugConsole.show();
                }
            }
        }
        this.runButton.onclick = DebugConsole.evaluate;
    }
};


addLoadEvent(function () {DebugConsole.init();});

/* MOD Shaikh
function cancelRightClick(){
    var allImages = document.getElementsByTagName('IMG');
     for(var i=0; i< allImages.length;i++){
          var image = allImages[i];
          image.oncontextmenu = function(e) {
              alert("Copyright Diageo plc 2007");
              return false;
          };
     }
}
addLoadEvent(cancelRightClick);
*/


/**
* Author : Goc Du
*/
/**************************************************************************************************
* These functions allow a user to set character limit on any form field.
*
* To use this function, type something like this:
* setCharMax(50,'ITEM_ATT40_0','remChars');
* where 50 is the character limit and ITEM_ATT40_0 is the ID of the text area element and remChars is the ID
* of the the html code just below.
*
* Including this html code: <div>You have <span id="remChars"></span> character<span id="single">s</span> remaining.</div>
* will display how many characters you have left as you type.
**************************************************************************************************/

function setCharMax(charMax,fieldId,charInfo){
  var len = document.getElementById(fieldId).value.length;
  document.getElementById(fieldId).onkeydown = function(){charLengthCheck(charMax,fieldId,charInfo);}
  document.getElementById(fieldId).onkeyup = function(){charLengthCheck(charMax,fieldId,charInfo);}
  document.getElementById(fieldId).onfocus = function(){charLengthCheck(charMax,fieldId,charInfo);}
  document.getElementById(charInfo).innerHTML = charMax-len+" ";
}

function charLengthCheck(charMax,fieldId,charInfo){
  var len = document.getElementById(fieldId).value.length;
  if (document.getElementById(charInfo)){
    if (len == charMax+1){
      document.getElementById(charInfo).innerHTML = 0+" ";
    } else {
      document.getElementById(charInfo).innerHTML = charMax-len+" ";
    }
  }
  if (document.getElementById(fieldId).value.length > charMax) {
    document.getElementById(fieldId).value = document.getElementById(fieldId).value.substr(0,charMax);
  }
}

/*************************************************************************************************/




/*
 * TODO: This doesnt work. Silly Me! Always seems to produce a lightbox with the default sizes. Not sure where the default sizes come from.
 * Possibly the CSS? Need to work this out.
 */
function openGreyBox(name, url, length, width) {
  var cGB= new GreyBox();
  cGB.setCenterWindow(true);
  cGB.setDimension(length,width);        
  return cGB.show(name, url, length, width)
}

function openGreyBox(name, url) {
  var cGB= new GreyBox();
//  cGB.setCenterWindow(true);
//  cGB.setDimension(600,555);        
  return cGB.show(name, url, 600, 555)
}


function delayedSave(delay) {
  setTimeout("embeddedSave()", delay);
}

function delayedReload(delay) {
    setTimeout("window.location.reload()", delay);
}

function delayedReplace(url, delay) {
  setTimeout("location.replace('" + url + "')", delay);
}



/**************************************************************************************************
* This function allows file type restriction for uploading files. Simply call the function with comma separated
* list of file type extensions you wish to allow and ensure that you include the ID of the upload element last.
* You can specify as many file types as you want.
* e.g.
* allowedFileTypes('jpg','pdf','gif','item_file');
**************************************************************************************************/
function allowedFileTypes() {
  if (document.getElementById(arguments[arguments.length-1]).value!="") {
    var fileValue = document.getElementById(arguments[arguments.length-1]).value;
    var extensionPos = fileValue.lastIndexOf(".");
    var extension = fileValue.substr(extensionPos,fileValue.length);
    var extensionList="";
    for (i=0; i<arguments.length-1; i++){
      if (i==arguments.length-2){
        extensionList += arguments[i];
      }
      else {
        extensionList += arguments[i]+", ";
      }
    }
    for (i=0; i<arguments.length-1; i++){
      if (extension.toLowerCase()=="."+arguments[i].toLowerCase()){
        return true;
      }
      else {
        alert("Please upload only with the following file types:\n"+extensionList);
        return false;
      }
    }
  }
}


/**************************************************************************************************
* Extracting image id from an item-link def and inputting the value in a specific metadata
* Only works with images and picks up the 1st image linked Id
*
**************************************************************************************************/

function extractImgIdAddField(link,field){
 var id=document.getElementById(link).getElementsByTagName('img');
 var src = '"'+(id[0].src)+'"';
 var start = src.indexOf('ITEM_ENT_ID=')+12;
 var finish = src.indexOf('&ITEM_VERSION');
 var extract = src.substring(start,finish);

document.getElementById(field).value=extract;
}


var createElement = function(properties) {
    var element = null;
    if(properties && properties.tag) {
      element = document.createElement(properties.tag);
    if(properties.src) {element.setAttribute("src", properties.src);}
    if(properties.className) {element.className = properties.className;}
    if(properties.innerText) {element.appendChild(document.createTextNode(properties.innerText));}
    if(properties.id) {element.setAttribute("id",properties.id);}
    if(properties.type) {element.setAttribute("type",properties.type);}
    if(properties.href) {element.setAttribute("href",properties.href);}
    if(properties.value) {element.value = properties.value;}
    }
    return element;
  };


/******
For site map, allows users to click on list to open/close them. This is in cojunction with css styling which needs to be updated for greater depth of opening/closing lists
******/

function clickableList(item){
    $(item).click(function(){
        $(item).parent().toggleClass('expanded');
        $(item).toggleClass('expanded');
        return false;
      })
}

$(document).ready(function() {
$("#sitemap li span").each(
   function(){
     clickableList(this); 
   });
 });



// Limit popup entries on CMS homepage

function limitEntry(id, context, linkId, allowedValue) {

    if((id == 931) && ($("li.news li").size() < allowedValue)) {
        linkingGreyBox('Link Primary Stories', context + '/cms/popups/link_news_grid', 700, 900, linkId);
        return false;
    } else if(id == 1194 && $("li.news li").size() < allowedValue) {
        linkingGreyBox('Link Primary Stories', context + '/cms/popups/link_news_bahasa', 700, 900, linkId);
        return false;
    } else if(id == 900 && $("li.videos li").size() < allowedValue) {
        linkingGreyBox('Link Primary Videos', context + '/cms/popups/link_feed_video', 700, 900, linkId);
        return false;
    } else if(id == 996 && $("li.gallery li").size() < allowedValue) {
        linkingGreyBox('Link Primary Gallery', context + '/cms/popups/link_gallery_v2', 700, 900, linkId);
        return false;
    } else if(id == 36 && $("#secondaryNews li").size() < allowedValue) {
        linkingGreyBox('Link News',context + '/cms/popups/link_news_secondary',700,900,linkId);
        return false;
    } else if(id == 1190 && $("#secondaryNews li").size() < allowedValue) {
        linkingGreyBox('Link News',context + '/cms/popups/link_news_secondary_bahasa',700,900,linkId);
        return false;
    } else{
        alert("Only " + allowedValue + " entries are allowed.");
    }
}

function limitPopupEntry(noOfEntries,allowedValue) {
    if(noOfEntries == (allowedValue-1)) {
        parent.parent.GB_hide();
    }
}



