
$(document).ready(function(){
    $.fn.addHover = function(hoverStyle) {
        $(this).hover(function() {
        $(this).addClass(hoverStyle);
        }, function() {
        $(this).removeClass(hoverStyle);
        });
    };
$("div#rightModulesWrapper div.toggleButton").addHover("showHover");
$("div#rightModulesWrapper div.toggleButton").click(function(event) {
     event.preventDefault();
     toggleModule(this.id);

   });
if (isFlashEnabled())
  {
    $('div#leftModulesWrapper div.type_flash').addClass('type_flash_visible').removeClass('type_flash');
  }
else
  {
    $('div#leftModulesWrapper div.type_image').addClass('type_image_visible').removeClass('type_image');
  }
if ( $("#news").length > 0 ) {
       $.ajax({
        url: '/C12576F7004CB55D/(wGetParams)/news?OpenDocument&Lang=En',
        success: function(data) {
          loadNews(data);
        }
       });
}
if ( $("#quotediv").length > 0 ) {
var chart = new FusionCharts("/C12576F7004CB55D/lkpResources/Line/$file/Line.swf", "ChartId", "230", "150", "0", "0");
chart.setDataURL("/C12576F7004CB55D/quoteData.xml?ReadForm&unique="+getUniqueKey());		   
chart.render("quotediv");
}
$("#langSelection").change (function(){
    var newLang=$("#langSelection option:selected")[0].value;
    setLangCookie(newLang)
    changeLanguage(newLang);
    }
);
$("#menu").treeview({ 
   collapsed: true, 
   animated: "fast", 
   persist: "location", 
   urlToLoad: "", 
   unique: true 
   }); 
$('div.menuEntryValue').bind('mouseover', jsddm_open);
$('div.menuEntryValue').bind('mouseout',  jsddm_timer);
$('#searchButton').click(function(event) {
   doSearch('En');
   return false;
   });
$('#search').keyup(function(e) {
  if(e.keyCode == 13) {
     doSearch('En');
     return false;
  }
});
$("#search").click(function(event){
     var curValue=$(this).val();
     var defaultValue='Search...';
     if (curValue==defaultValue)
       {
          $(this).val("");
       }
    }
);
$("#search").blur(function(event){
     var curValue=trim($(this).val());
     var defaultValue='Search...';
     if (curValue=="")
       {
          $(this).val(defaultValue);
       }
    }
);
if (typeof(fundsIDs)!="undefined") {
    for (i=0;i<fundsIDs.length;i=i+1) {
           loadFundCombos(fundsIDs[i],fundsComboValues[i]);
           loadFundDetails(fundsIDs[i],fundsComboDefaultValues[i]);
    }
$('#centerWrapper .fundsSelector').change(function(event) {
    loadFundDetails(strRight($(this).attr('id'),"fundsSelector"),$(this).val());
   });
}
removeModuleExtraCode("#rightModulesWrapper .withoutBox");
});
$(window).load(function() {
    resizeHeader();
  setFooterAtBottom();

});

$(window).resize(function() {
    resizeHeader();
  setFooterAtBottom();
});

function resizeHeader()
{
    rightCornerObj=$("#headerRightCorner");
    windowWidth = $(window).width();
    contentWidth=$("#header").width();
    var hackWasStarted=false;
    var rightCornerWidth=parseInt($(rightCornerObj).css("width"));
    if (windowWidth-(2*rightCornerWidth)>=contentWidth) {
        $("#gradient").css("width",windowWidth+"px");
        $(rightCornerObj).css("left",(windowWidth-rightCornerWidth)+"px");
        $(rightCornerObj).css("display","block");
    }
    else {
        $(rightCornerObj).css("display","none");
        gradientWidth=(contentWidth>windowWidth)?contentWidth:windowWidth;
        $("#gradient").css("width",gradientWidth+"px");
    }
}
function loadNews(ajaxData)
{
var newsContent=strLeft(strRight(ajaxData,'<div id="newsContent">'),"</div>");
var delayValue =strLeft(strRight(ajaxData,'<div id="showDuration">'),"</div>");
var allNewsLabel=strLeft(strRight(ajaxData,'<div id="allNewsLabel">'),"</div>");
$("#news").html(newsContent);
$("#allNewsLabel").html(allNewsLabel);
$("#news").newsTicker(delayValue*1000);
}
function setFooterAtBottom()
{
      stdFooterSpacerHeight=10;
      footerSpacerObj=$("#footerSpacer");
      footerSpaceHeight=$(footerSpacerObj).height();
      contentHeight=$("#contentWrapper").height();
      headerHeight=$("#headerWrapper").height();    
      footerHeight=$("#footerWrapper").height();
      toplinkHeight=$("#top").height();
      windowHeight=$(window).height();
      newHeight=windowHeight-toplinkHeight-contentHeight-headerHeight-footerHeight;
      if (newHeight<stdFooterSpacerHeight) {
         newHeight=stdFooterSpacerHeight;
      }
      $(footerSpacerObj).css("height",newHeight+"px");
}
function strLeft(sourceStr, keyStr){
return (sourceStr.indexOf(keyStr) == -1 | keyStr=='') ? '' : sourceStr.split(keyStr)[0];
} 
function strRight(sourceStr, keyStr){
idx = sourceStr.indexOf(keyStr);
return (idx == -1 | keyStr=='') ? '' : sourceStr.substr(idx+ keyStr.length);
}
function trim(str)
{
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); 
}
function toggleModule(clickedObjID)
{
var divIDToModify=strLeft(clickedObjID,"_")+"_module";
$("div#rightModulesWrapper div#"+divIDToModify).slideToggle('normal', function() {
       setFooterAtBottom();
       resizeHeader();
  });
var buttonObj=$("div#rightModulesWrapper div#"+clickedObjID);
if (buttonObj[0].className.indexOf("toCollapse") == -1)
{
   $(buttonObj).removeClass("toExpand").addClass("toCollapse");
}
else
{
   $(buttonObj).removeClass("toCollapse").addClass("toExpand");
}
}
function changeLanguage(newLanguage)
{
    var curURL=window.location.href;
    var curLang=strRight(curURL,"Lang=").substr(0,2);
    var newURL="";
   if (curLang=="")
     {
       var prefix="";
       if (curURL.toLowerCase().match(/C12576F7004CB55D/)==null) {
          newURL="/C12576F7004CB55D/(DocsById)/Home?OpenDocument&amp;Lang="+newLanguage;
       }
       else if (curURL.toLowerCase().match(/opendocument/)==null)
       {
          prefix="?OpenDocument";
          newURL=curURL+prefix+"&amp;Lang="+newLanguage;
       }
     }
   else
     {
        replaceRegExp= new RegExp("&Lang="+curLang)
        newURL=curURL.replace(replaceRegExp, "&amp;Lang="+newLanguage);
        if (newURL==curURL) {
            replaceRegExp= new RegExp("&amp;Lang="+curLang)
            newURL=curURL.replace(replaceRegExp, "&amp;Lang="+newLanguage);
        }
     }
     if (newURL!="")
       {
         location=newURL;
       }
}
function isFlashEnabled()
{
var requiredMajorVersion = 8;
var requiredMinorVersion = 0;
var requiredRevision = 0;
return DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
}
function getUniqueKey()
{
   var curDate=new Date();
   var curYear=curDate.getFullYear();
   var curMonth=curDate.getMonth();
   var curDay=curDate.getDay();
   var curHour=curDate.getHours();
   var curMinute=curDate.getMinutes();
  return curYear+curMonth+curDay+curHour+curMinute
}
function loadFundDetails(fundID,docID) {
     $.ajax({
           url: "/C12576F7004CB55D/(lkpFundsDetails)/"+docID+"?OpenDocument&Lang=En",
           dataType: "html",
           cache : false,
           success: function(content){
 $("#fundsContent"+clearID(fundID)).html(content);
           }
        }
     )
}
function  loadFundCombos(categoryID,values) {
var output = [];
var inputArray=values.split("##");
$.each(inputArray, function(key, value)
{
  id=strRight(value,"|");
  label=strLeft(value,"|");
  output.push('<option value="'+ id +'" id="fundkey'+clearID(id)+'">'+label  +'</option>');
});
$('#fundsSelector'+clearID(categoryID)).html(output.join(''));
}
function  clearID(curID) {
    return curID.replace(/\(/gi,"").replace(/\)/gi,"");
}
function removeModuleExtraCode(selector) {
var allFreeWithoutBox=$(selector);
  if (allFreeWithoutBox.length>0) { 
     var lastp=$(allFreeWithoutBox).find("p");
     $(lastp).each(function() {
       var content=$.trim($(this).html());
       if (content.toLowerCase()=="<br>") {
           $(this).addClass("minimumHeight");
       } 
     });
     $(allFreeWithoutBox).each(function() {
         var continueLoop=true;
         var curModuleClass=$(this)[0].className;
         $($(this).find("*").get().reverse()).each(function(index) {
               if (continueLoop) {
	   var curNodeName=this.nodeName.toUpperCase();
	   var isEmpty=false;
	   if (this.previousSibling==null) {
                        continueLoop=false;
                   } else {
   	   	if (this.previousSibling.nodeValue==null) {
		      isEmpty=true;
		   } else {
		      isEmpty=(this.previousSibling.nodeValue.replace(/\n/gi,"")=="");
		   }
		   if ((curNodeName=="BR")  && (isEmpty)) {
	      	       $(this).remove();
		   }else if (curNodeName=="BR")   {
	       	      $(this).remove();
		             continueLoop=false
		   } else {
	 	            continueLoop=false;
	 	  }
                   }
              }
          });
     });
  }
}
var timeout         = 100;
var closetimer		= 0;
var ddmenuitem      = 0;
var orgMenuLeftCorrection = 0;
function jsddm_open()
{	
	jsddm_canceltimer();
	jsddm_close();
	curid=strRight($(this).attr('id'),"_");
	var subMenu=$('#sub_'+curid).eq(0);
	if (isNaN(orgMenuLeftCorrection))
	   {
                       orgMenuLeftCorrection=0;
                   }
	if (orgMenuLeftCorrection==0)
                   {
	      orgMenuLeftCorrection=parseInt(subMenu.css('margin-left'));
                   }
	var leftCorrection=0;
	var topCorrection=0;
	var eltPosition= $(this).position();
	if (leftCorrection!=0)
  	   {
	      var newValue=orgMenuLeftCorrection-leftCorrection;
	      subMenu.css('margin-left', newValue+'px')
	   }
	if (topCorrection!=0)
  	   {
	      subMenu.css('top', topCorrection-22+'px')
	   }
	ddmenuitem = $('#sub_'+curid).eq(0).css('visibility', 'visible');
}
function jsddm_close()
{	if(ddmenuitem) ddmenuitem.css('visibility', 'hidden');}
function jsddm_timer()
{	closetimer = window.setTimeout(jsddm_close, timeout);}
function jsddm_canceltimer()
{	if(closetimer)
	{	window.clearTimeout(closetimer);
		closetimer = null;}}
function doSearch()
{
  var valueToSearch=document.getElementById('search').value;
  var defaultValue='Search...';
  
  if ((trim(valueToSearch)!="") && ( valueToSearch!=defaultValue ))
  {
    valueToSearch=removeForbiddenChars(valueToSearch);
    $("#search")[0].value=valueToSearch;
    valueToSearch=valueToSearch.replace(/\s/,"+AND+");
    $.ajax({
	url: '/C12576F7004CB55D/(search_En)?SearchView&Query='+valueToSearch+'&SearchOrder=1&Lang=En',
	success: function(data) {
	  loadSearchResult(data);
	},
	error : function (data) {
	 alert('error');
                }
     });
  }
}
function removeForbiddenChars(valueToSearch) {
   return valueToSearch.replace(/"/gi,"").replace(/%27/gi,"").replace(/'/gi,"").replace(/%22/gi,"").replace(/%27/gi,"").replace(/%3C/gi,"").replace(/%3E/gi,"").replace(/</gi,"").replace(/>/gi,"");
}
function loadSearchResult(data)
{
  var meaningfulDatas=strLeft(strRight(data,"<body>"),"</body>");
  $('#centerWrapper').html(meaningfulDatas);
}
function setSameLineHeight(nbRows)
{
   for (i=1;i<=nbRows;i=i+1)
    {
       var allCols=$('.row'+i);
       var curHeights=new Array();
       for (j=0;j<allCols.length;j=j+1)
       {
	curHeights[j]=allCols[j].clientHeight;
       }
       var maxHeight=Array.max(curHeights);
       for (j=0;j<allCols.length;j=j+1)
       {
	$('.row'+i+".col"+(j+1)).height(maxHeight);
       }
    }
}
function setLangCookie(lang)
{
   setCookie('langpref',lang,'/');
   return true;
}
function readLangCookie()
{
   return getCookie('langpref');
}
function setCookie (name, value, path, domain, secure) {
       window.document.cookie = name + "=" + escape(value) +
         "; expires=Mon 01-Jan-2050 00:00:00" +
         ((path) ? "; path=" + path : "") +
         ((domain) ? "; domain=" + domain : "") +
         ((secure) ? "; secure" : "");
 }
function getCookieVal(offset){
var endstr=window.document.cookie.indexOf(";", offset);
if(endstr==-1) endstr=window.document.cookie.length;
return unescape(window.document.cookie.substring(offset, endstr));
}
function getCookie(name){
	var arg=name+"=";
	var alen=arg.length;
	var clen=window.document.cookie.length;
	var i=0;
	while (i < clen){
	var j=i+alen;
	if (window.document.cookie.substring(i, j)==arg) return getCookieVal(j);
	i=window.document.cookie.indexOf(" ", i)+1;
	if (i==0) break;
	}
	return "";
}
function resetCookie (name, value, path, domain, secure) {
       window.document.cookie = name + "=" + escape(value) +
         "; expires=Mon 01-Jan-1970 00:00:00" +
         ((path) ? "; path=" + path : "") +
         ((domain) ? "; domain=" + domain : "") +
         ((secure) ? "; secure" : "");
 }
/**
 * FusionCharts: Flash Player detection and Chart embed 
 * 
 * Morphed from SWFObject (http://blog.deconcept.com/swfobject/) under MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof infosoftglobal == "undefined") var infosoftglobal = new Object();
if(typeof infosoftglobal.FusionChartsUtil == "undefined") infosoftglobal.FusionChartsUtil = new Object();
infosoftglobal.FusionCharts = function(swf, id, w, h, debugMode, registerWithJS, c, scaleMode, lang){
	if (!document.getElementById) { return; }
	
	//Flag to see whether data has been set initially
	this.initialDataSet = false;
	
	//Create container objects
	this.params = new Object();
	this.variables = new Object();
	this.attributes = new Array();
	
	//Set attributes for the SWF
	if(swf) { this.setAttribute('swf', swf); }
	if(id) { this.setAttribute('id', id); }
	if(w) { this.setAttribute('width', w); }
	if(h) { this.setAttribute('height', h); }
	
	//Set background color
	if(c) { this.addParam('bgcolor', c); }
	
	//Set Quality	
	this.addParam('quality', 'high');
	
	//Add scripting access parameter
	this.addParam('allowScriptAccess', 'always');
	
	//Pass width and height to be appended as chartWidth and chartHeight
	this.addVariable('chartWidth', w);
	this.addVariable('chartHeight', h);
	//Whether in debug mode
	debugMode = debugMode ? debugMode : 0;
	this.addVariable('debugMode', debugMode);
	//Pass DOM ID to Chart
	this.addVariable('DOMId', id);
	//Whether to registed with JavaScript
	registerWithJS = registerWithJS ? registerWithJS : 0;
	this.addVariable('registerWithJS', registerWithJS);
	
	//Scale Mode of chart
	scaleMode = scaleMode ? scaleMode : 'noScale';
	this.addVariable('scaleMode', scaleMode);
	//Application Message Language
	lang = lang ? lang : 'EN';
	this.addVariable('lang', lang);
}
infosoftglobal.FusionCharts.prototype = {
	setAttribute: function(name, value){
		this.attributes[name] = value;
	},
	getAttribute: function(name){
		return this.attributes[name];
	},
	addParam: function(name, value){
		this.params[name] = value;
	},
	getParams: function(){
		return this.params;
	},
	addVariable: function(name, value){
		this.variables[name] = value;
	},
	getVariable: function(name){
		return this.variables[name];
	},
	getVariables: function(){
		return this.variables;
	},
	getVariablePairs: function(){
		var variablePairs = new Array();
		var key;
		var variables = this.getVariables();
		for(key in variables){
			variablePairs.push(key +"="+ variables[key]);
		}
		return variablePairs;
	},
	getSWFHTML: function() {
		var swfNode = "";
		if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) { 
			// netscape plugin architecture			
			swfNode = '<embed type="application/x-shockwave-flash" src="'+ this.getAttribute('swf') +'" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'"  ';
			swfNode += ' id="'+ this.getAttribute('id') +'" name="'+ this.getAttribute('id') +'" ';
			var params = this.getParams();
			 for(var key in params){ swfNode += [key] +'="'+ params[key] +'" '; }
			var pairs = this.getVariablePairs().join("&");
			 if (pairs.length > 0){ swfNode += 'flashvars="'+ pairs +'"'; }
			swfNode += '/>';
		} else { // PC IE			
			swfNode = '<object id="'+ this.getAttribute('id') +'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'">';
			swfNode += '<param name="movie" value="'+ this.getAttribute('swf') +'" />';
			var params = this.getParams();
			for(var key in params) {
			 swfNode += '<param name="'+ key +'" value="'+ params[key] +'" />';
			}
			var pairs = this.getVariablePairs().join("&");			
			if(pairs.length > 0) {swfNode += '<param name="flashvars" value="'+ pairs +'" />';}
			swfNode += "</object>";
		}
		return swfNode;
	},
	setDataURL: function(strDataURL){
		//This method sets the data URL for the chart.
		//If being set initially
		if (this.initialDataSet==false){
			this.addVariable('dataURL',strDataURL);
			//Update flag
			this.initialDataSet = true;
		}else{
			//Else, we update the chart data using External Interface
			//Get reference to chart object
			var chartObj = infosoftglobal.FusionChartsUtil.getChartObject(this.getAttribute('id'));
			chartObj.setDataURL(strDataURL);
		}
	},
	setDataXML: function(strDataXML){
		//If being set initially
		if (this.initialDataSet==false){
			//This method sets the data XML for the chart INITIALLY.
			this.addVariable('dataXML',strDataXML);
			//Update flag
			this.initialDataSet = true;
		}else{
			//Else, we update the chart data using External Interface
			//Get reference to chart object
			var chartObj = infosoftglobal.FusionChartsUtil.getChartObject(this.getAttribute('id'));
			chartObj.setDataXML(strDataXML);
		}
	},
	render: function(elementId){
		var n = (typeof elementId == 'string') ? document.getElementById(elementId) : elementId;
		n.innerHTML = this.getSWFHTML();
		return true;		
	}
}
// ------------ Fix for Out of Memory Bug in IE in FP9 ---------------//
/* Fix for video streaming bug */
infosoftglobal.FusionChartsUtil.cleanupSWFs = function() {
	if (window.opera || !document.all) return;
	var objects = document.getElementsByTagName("OBJECT");
	for (var i=0; i < objects.length; i++) {
		objects[i].style.display = 'none';
		for (var x in objects[i]) {
			if (typeof objects[i][x] == 'function') {
				objects[i][x] = function(){};
			}
		}
	}
}
// Fixes bug in fp9
infosoftglobal.FusionChartsUtil.prepUnload = function() {
	__flash_unloadHandler = function(){};
	__flash_savedUnloadHandler = function(){};
	if (typeof window.onunload == 'function') {
		var oldUnload = window.onunload;
		window.onunload = function() {
			infosoftglobal.FusionChartsUtil.cleanupSWFs();
			oldUnload();
		}
	} else {
		window.onunload = infosoftglobal.FusionChartsUtil.cleanupSWFs;
	}
}
if (typeof window.onbeforeunload == 'function') {
	var oldBeforeUnload = window.onbeforeunload;
	window.onbeforeunload = function() {
		infosoftglobal.FusionChartsUtil.prepUnload();
		oldBeforeUnload();
	}
} else {
	window.onbeforeunload = infosoftglobal.FusionChartsUtil.prepUnload;
}
/* Add Array.push if needed (ie5) */
if (Array.prototype.push == null) { Array.prototype.push = function(item) { this[this.length] = item; return this.length; }}
/* Function to return Flash Object from ID */
infosoftglobal.FusionChartsUtil.getChartObject = function(id)
{
  if (window.document[id]) {
      return window.document[id];
  }
  if (navigator.appName.indexOf("Microsoft Internet")==-1) {
    if (document.embeds && document.embeds[id])
      return document.embeds[id]; 
  } else {
    return document.getElementById(id);
  }
}
/* Aliases for easy usage */
var getChartFromId = infosoftglobal.FusionChartsUtil.getChartObject;
var FusionCharts = infosoftglobal.FusionCharts;
