
/*-----------------------------------------------------------------------------*/ 
/* Utility Javascript
/*-----------------------------------------------------------------------------*/ 
/*
  - AKHJV
  - Date: September 21, 2011
  - Version:1.0
  - Description: Javascript functions used on the Marketing Portion of the website. Includes Navigation, Ticker, Lighbox, Banner Rotate and News Feed 
  - Changes: -- 
*/

/*-----------------------------------------------------------------------------*/ 
/* Generic Functions
/*-----------------------------------------------------------------------------*/

/*### Fix relative paths in Nav ###*/
/*--------------------------------------------------*/ 
/* Note: Need to make reusable. Requires Jquery
/*--------------------------------------------------*/ 
/*-- "indexOf" Correction function for IE --*/ 

/*if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function (obj, start) {
    for (var i = (start || 0); i < this.length; i++) {
      if (this[i] == obj) {
        return i;
      }
    }
    return -1;
  }
}*/

/*--------------------------------------------------*/ 

function linkLevel(lvl) {
	var dir = ["./","../","../../", "../../../"];
	
	$(".navlink").each(function(i, lnk) {	
		/*Check for URL in list*/
		if ($(lnk).children().attr('href')){
			var href = $(lnk).children().attr("href").split("../")[1];
			$(lnk).children().attr("href", dir[lvl]+href);
		}
		/*Check for image*/
		else if ($(lnk).attr('src')){
			href = $(lnk).attr("src").split("../")[1];
			$(lnk).attr("src", dir[lvl]+href)
			}
	});
};

function relativeNavFix(){	
		var url = document.URL,
			section = ["products", "services", "aboutus"],
			slen = section.length;
		
			for (i=0;i<slen;i++){
				var s = section[i],
				regex = new RegExp (s,"i");
				if (url.match(regex)){
					var frag = url.split("/")
					for (m in frag) {
						if (frag[Number(m)] == s){
							if (frag[Number(m)+1] !== "index.shtml"){
									linkLevel(2);
							}
						}
					}
					//var indx = frag[frag.indexOf(s)+1]								
					//if (indx !== "index.shtml" ){
					//linkLevel(2);
					//};
				}
			}
			
			if (url.match(/sitemap/i)) {
					linkLevel(0);
			};	
}
relativeNavFix();


/*### Return a single variable from a URL string ###*/
/*--------------------------------------------------*/ 
function GetUrlValue() {
	var strQueryString="";
	var hasQueryString = document.URL.indexOf('?');
		
	if (hasQueryString != -1){
			strQueryString = document.URL.substring(hasQueryString+1, document.URL.length);
			return strQueryString;
		}
} 
	 
/*###  Convert RSS Date to Long or short Date ###*/ 
/*-----------------------------------------------*/ 
function dateConversion(date, type) {
	var regex = /\d\d\s\w\w\w\s\d\d\d\d/g,
		month = {"Jan":"01", "Feb":"02", "Mar":"03", "Apr":"04", "May":"05", "Jun":"06", "Jul":"07", "Aug":"08", "Sep":"09", "Oct":"10", "Nov":"11", "Dec":"12"},
		lng_month = {"Jan":"January", "Feb":"Februray", "Mar":"March", "Apr":"April", "May":"May", "Jun":"June", "Jul":"July", "Aug":"August", "Sep":"September", "Oct":"October", "Nov":"November", "Dec":"December"},
	
		convert = date.match(regex).toString().split(" "),
		final = month[convert[1]] + "/" + convert[0] + "/" + convert[2];
	
	if (type=="long") {
		final = lng_month[convert[1]] + " " + convert[0] + ", " + convert[2];
	} else if (type=="short") {
		final = convert[0] + " " + convert[1] + ", " +convert[2];  
	} else if (type=="euro") {
		final =  toNumber(convert[0])+ " " +lng_month[convert[1]] + " " + convert[2];
	}
	
	return final; 
}


/*### Shorten Strings for messages in a table ###*/ 
/*-----------------------------------------------*/ 
function stringConcat(strLen, strRaw, htmlStrip) {
	if (strLen && strRaw.length>strLen) { 
		
		var patt1 = new RegExp("[\\s \\S]{"+strLen+"}","g"),
			strRaw = strRaw.match(patt1)[0];
			
		if (htmlStrip) {
			var strip = /<(?:.|\s)*?>/g;
				strRaw = strRaw.replace(strip, ""); 
		}
		
		var strArray = strRaw.split(" "),
			len = strArray.length,
			complete = strArray.slice(0,(len-1)).join(" ")+"...";
		
		return complete;
	} else {
		return strRaw;	
	}
}
	


/*-----------------------------------------------------------------------------*/ 
/* Top and Left Navigation Highlight and Submenu
/*-----------------------------------------------------------------------------*/
/*
  - AKHLEG
  - Date: September 21, 2011
  - Version:1.0
  - Description:  Top and Left Navigation Sub Bars display and highlighting location for the user on the page
  - Changes: -- 
*/ 

if (!path) {
	var path=false;	
}

// Detect which directory the page resides in //
function thiz(id)
	{
		if (typeof id == "string")
		{   
			return document.getElementById(id);
		}
		else if (typeof id == "object")
		{
			return id;	 		
		}
	}

function hasCssClass(id, cssClass)
	{ 
		
		var cssClassList = thiz(id).className;
		
		if (cssClassList.length == 0 )
		{
			return false;
		}
		else
		{
			if (cssClassList.indexOf(cssClass) >= 0)
			{
				return true;
			}
			return false;
		}
	}

function addCssClass(id, cssClass)
	{
		var cssClassList = thiz(id).className;
		if (cssClassList.length == 0)
		{
			thiz(id).className = cssClass;
			return true;
		}
		
		if (cssClassList.indexOf(cssClass) >= 0)
		{
			return false;
		}
		else
		{
			var classArray = cssClassList.split(" ");
			classArray.push(cssClass);
			thiz(id).className = classArray.join(" ");
			return true;
		}
	}

function removeCssClass(id, cssClass)
	{
		var cssClassList = thiz(id).className;
		
		//alert(cssClassList);
		
		if (cssClassList.length == 0)
		{
			return false;
		}
		
		if (cssClassList.indexOf(cssClass) >= 0)
		{
			var classArray = cssClassList.split(" ");
			var newClassList = new Array();
			for (x in classArray)
			{
				if (classArray[x] != cssClass)
				{
					if (classArray[x] != "")
					{
						newClassList.push(classArray[x]);
					}
				}
			}
			thiz(id).className = newClassList.join(" ");
			return true;
		}
		else
		{
			return false;
		}
	}

function toggleCssClass(cssClass)
	{
		if (hasCssClass(this, cssClass))
		{
			removeCssClass(element, cssClass);
		}
		else
		{
			addCssClass(element, cssClass);
		}
	}

function toggleParentCssClass(element, cssClass)
	{
		var targetElement = element.parentNode;
		
		if (hasCssClass(targetElement, cssClass))
		{
			removeCssClass(targetElement, cssClass);
		}
		else
		{
			addCssClass(targetElement, cssClass);
		}
	}

function urlParser(uri)
	{
		var urlPattern=new RegExp("^http[s]?://[a-zA-Z0-9_\.:]+/{1}"); 
		// was ("^[a-z]{4,5}://[A-Za-z0-9.]+/{1}");
		this.raw = uri;
		if (path){this.raw=path};
		
		this.server = urlPattern.exec(this.raw);
		this.subDirs = this.raw.replace(this.server,"").split("/");
		this.file = this.subDirs[this.subDirs.length - 1];
		
		this.match = function (query)
		{
			if (this.raw.indexOf(query) >= 0)
			{ return true;}
			else
			{ return false;}
		}
	}


function here()
	{
		
		this.uri = new urlParser(document.URL);
		
		if (path) {
			this.uri = new urlParser(path);
		}
		
		if (document.referrer != '')
		{
			this.ref = new urlParser(document.referrer);
			this.hasRef = true;
		}
		else
		{
			this.ref = "";
			this.hasRef = false;
		}
	}

function changeVisibility(element)
	{
		if (hasCssClass(element, "hide"))
		{
			removeCssClass(element, "hide");
		}
		else
		{
			addCssClass(element, "hide");
		}
	}

function hideEl(element)
	{
		addCssClass(element, "hide");
	}

function showEl(element)
	{
		removeCssClass(element, "hide");
	}

function changeSelected(element)
	{
		if (hasCssClass(element, "selected"))
		{
			removeCssClass(element, "selected");
		}
		else
		{
			addCssClass(element, "selected");
		}
	}

function synchMenu(element)
	{
		menu_main = element + "_main";
		menu_sub = element + "_sub";
		changeSelected(menu_main);
		if (menu_sub!="home_sub") {
			changeVisibility(menu_sub);
		}
	}

function returnDocument()
	{
		var file_name = document.location.href;
		var end = (file_name.indexOf("?") == -1) ? file_name.length : file_name.indexOf("?");
		return file_name.substring(file_name.lastIndexOf("/")+1, end);
		
	}

function initMenu()
	{
		var menu = document.getElementById("nav");
		var here = document.location.href; // May need to be document.URL when used on the server.
	
	
		if (menu != null)
		{
			var aList = menu.getElementsByTagName("a"); 
			var isSplit = here.split("/");  
			var dir = isSplit[isSplit.length-2];
			var base = here.split("/").splice(0,4).join("/");								

			
			for (anchor in aList)
			{
				
				
				if (aList[anchor].parentNode != undefined)
				{
					/*relative link fix for IE*/
						var ieHref = aList[anchor].href.split("../"); 
					
						if (ieHref.length > 1) {
						    aList[anchor].href.split("../")
							aList[anchor].href = base.concat("/",ieHref[ieHref.length-1]);
						};
					
					if (aList[anchor].parentNode.nodeName == "LI" && aList[anchor].parentNode.getElementsByTagName("ul").length == 0)
					{
						aList[anchor].className = "none";
					} 				
				}
				
				if (aList[anchor] == here) 
				{
					aList[anchor].className = "here";
				}
				
				
				if (aList[anchor].href == here )
				{
					
					anchorParent = aList[anchor].parentNode;
			
					if (anchorParent.getElementsByTagName("ul").length == 0 && aList[anchor].className != "none")
					{
						aList[anchor].className = "closed";
					}
					while (anchorParent.nodeName != "DIV")
					{
						
						if (anchorParent.nodeName == "LI")
						{
						
							anchorParent.className = "open";
						}
		
						anchorParent = anchorParent.parentNode;
					}
				}
			}
		}
	}
	window.onload = initMenu;




/*### Top and Left Navigation Menu Render ###*/ 
/*-----------------------------------------------------------------------------*/ 

function topnav() {
	var myURL = new here();
	var topLevelLocation = myURL.uri.subDirs[1]; //grabs name of directory
	
	switch (topLevelLocation)
	{
	
		case "home":
		{
			synchMenu("home");
			break;
		}
		
		case "aboutus":
		{
			synchMenu("about");
			break;
		}
	
		case "products":  
		{
			synchMenu("prod");  
			
			switch (myURL.uri.subDirs[2])
			{
				case "calculator": {changeSelected("prod_calc"); break;}
				//case "consulting": {changeSelected("prod_ybc"); break;}//moved to services section
				case "yield-book": {changeSelected("prod_tyb"); break;}
				case "api": {changeSelected("prod_ybxml"); break;}
				case "fixed-income-indexes": {changeSelected("prod_citiind"); break;}
				case "add-in": {changeSelected("prod_ybaddin"); break;}
				default: {break;}
			}
			break;
		}
		
		case "services":  
		{
			synchMenu("serv");  
			
			switch (myURL.uri.subDirs[2])
			{
				case "workshops": {changeSelected("serv_work"); break;}
				case "consulting": {changeSelected("serv_cons"); break;}
				case "custom_training": {changeSelected("serv_cust"); break;}
				default: {break;}
			}
			break;
		}
	
	
		case "indexes":  
		{
			synchMenu("inde");  
			
			switch (myURL.uri.subDirs[2])
			{
				case "workshops": {changeSelected("inde_citi"); break;}
				case "consulting": {changeSelected("inde_rafi"); break;}
				default: {break;}
			}
			break;
		}
	
	default: {break;}
	}
}	

topnav();



/*-----------------------------------------------------------------------------*/ 
/*JQuery Banner Rotate: Home and Product Page */
/*-----------------------------------------------------------------------------*/ 
/*
  - AKH1
  - Date: September 21, 2011
  - Version:1.0
  - Description: Banner Rotate and Control bar functions
  - Changes: -- 
*/


/*Preload Images*/
function preloadImages(arrayOfImages) {
    
	var new_img = new Image();
	for (i in arrayOfImages) {
         new_img.src = arrayOfImages[i];
    }
	return arrayOfImages;
}

/*Create object*/
function bannerSet(id, interval, imgs, fadein, fadeout, links) {
	this.id = $(id);
	this.int = 0;
	this.imgs = imgs;
	this.fin = fadein;
	this.fout = fadeout;
	this.ctrl = $("#image_control");
	this.t = 0;
	this.rate = interval;
	this.url= links;
}

/*Apply Methods*/
bannerSet.prototype = {
    _this : "",
    /*Create initial values and functions that run only once*/
	init: function() {
        /*store as a pointer for future use - important for setTimeOut*/
		_this =  this;
		
		/*control bar objects*/
		var $bcon = _this.ctrl,
		    $bclr =  $("#image_control_color")
		
		/*hide the control bar on load*/
		$bcon.parent().hide();
		$bclr.hide();
		
		/*show and hide the bar on banner rollover*/
		_this.id.parent().mouseenter(function(){
		  $bcon.parent().fadeIn(200);
		  $bclr.fadeIn(200);
		}).mouseleave(function(){
		  $bcon.parent().fadeOut(200);
		  $bclr.fadeOut(200)
		});
		
		/*clear the control bar elements*/
		$bcon.empty()
		
		/*create buttons to skip to the next banner*/
		for (var i=0; i<_this.imgs.length;i++) {
			var newDiv = $("<div>").click(function() {				   
				_this.stop_loop();
				_this.int = parseInt($(this).index()-1);
				_this.rotate();
				$bcon.find(".pic_on").removeClass('pic_on');
				$(this).addClass('pic_on');
			});
			
			/*if its first in the list show that it is selected on load*/
			if (i==0) {
				newDiv.addClass("pic_on");
			}
			
			/*Append the buttons to the control bar*/
			$bcon.append(newDiv);
			/*add click function to the first link*/
			if (_this.url) {_this.bclick();}
		}
    }, 

	/*Rotate the image*/
  	rotate: function() {
		var $banner = _this.id,
		bannerArray = _this.imgs;
		
			/*interate to the next image - if at the end start over*/
			if (_this.int<(_this.imgs.length -1)){
				_this.int+=1;
			}
			else {
				_this.int=0;
			}
			
			/*Perform Fade Animation*/
			$banner.fadeOut(_this.fout, function(){
				var imgPath=(bannerArray[_this.int]);
				var altTxt = "Yield Book - World Wide"
				$banner.empty().append('<img src="'+imgPath+'" alt="'+altTxt+'" />');
				//Add click function if needed
				if (_this.url) {
					_this.bclick();
				}
				$banner.fadeIn(_this.fin);
			});
			
			/*Call the start function to continue the loop*/
			_this.start();
			
			/*adjust the control bar to match the banner location*/
			_this.ctrl.find(".pic_on").removeClass('pic_on');
		    _this.ctrl.find("div:eq("+parseInt(_this.int)+")").addClass('pic_on');
    },

	start:  function() {
		_this.t = setTimeout(_this.rotate, _this.rate);
	},
	
	stop_loop: function() {
		clearTimeout(_this.t);
	},
	bclick: function() {
		_this.id.children("img").unbind().css("cursor","pointer").click(function() {window.location=_this.url[_this.int];});
	}
	
	
};


/*-----------------------------------------------------------------------------*/ 
/*Jquery Index Ticker*/
/*-----------------------------------------------------------------------------*/ 
/*
  - AKHJV
  - Date: September 21, 2011
  - Version:1.0
  - Description: Grabs XML ticker data and generates the scrollbar on top of the page. Includes Plugin for rollover tip.
  - Changes: -- 
*/

function toNumber(val){
	if (val && (val!=="0.00")) {
		return Number(val) 
	} else {
		return val;	
	}
}

function tickerData() {
		/*see if the ticker bar exists on the page*/
		var $status_box = $('#ticker_bar');
		var xml_url = "../src/xml/ticker.xml"
		if (document.URL.match("products")){
			xml_url = "../../src/xml/ticker.xml"
		}
		
		
		if ($status_box.length != 0){
			/*Pull the index xml file*/
			$.ajax({
			   type: "GET",
			   url: xml_url, //need url from live xml
			   dataType: "xml",
			   cache: false,
			   success: function (xml) {
					
					/*HTML var for placing on page*/
					var ticker_data = ''
					
					/*Loop through each item*/
					$(xml).find("item").each(function(i) {
						/*cache 'this' for speed*/
						$this = $(this)
						
						/*Index object, empty tip string and color value*/
						var tip="",
							index = {},
							color = "black";
						
						/*text values*/
							index.name		= ["Index" ,$this.find("ticker").text()];
						    index.desc		= ["Name", $this.find("desc").text()];
						    index.currency	= ["Currency", $this.find("currency").text()];
						    index.hedged	= ["Hedged", $this.find("hedged").text()];
						    index.date		= ["Date", $this.find("value_date").text()];
						
						/*numeric values*/
							index.value 		= ["Index Value", toNumber($this.find("index_value").text())];
						    index.daily_return	= ["Daily Return", toNumber($this.find("total_daily_return").text())];
						    index.mtd_return	= ["MTD Return", toNumber($this.find("total_mtd_return").text())];
						    index.ytd_return	= ["YTD Return", toNumber($this.find("total_ytd_return").text())];				

													
						/*Adjust hedged vs no hedged text value*/
						if (index.hedged[1].toLowerCase == "n") {
							index.hedged[1]="No"	
						} else {
							index.hedged[1]="Yes"	
						};
						
						/*Change color of ticker if needed*/
						if (index.mtd_return[1] < 0) {/*change back to daily_return when hooked to live feed*/
						 color = "red";
						}
						
						/*initial ticker value when loop is first run*/
						if (i==0){
						  ticker_data = '<span class="head" title="">Citigroup Indexes '+index.date[1]+' Returns:</span>'
						}
						
						//alert(index.daily_return[1])
						
						/*Loop through and apply HTML*/
						for (key in index){
							if (index[key][1]){
								if (index[key][1] < 0){
									tip = tip+ "<div class="+color+"><span>"+index[key][0]+":</span>"+index[key][1]+"</div>"
								} else {
									tip = tip+ "<div><span>"+index[key][0]+":</span>"+index[key][1]+"</div>"
								}
							}
						}
						
						/*HTML template for ticker and tool tip*/
							index_data = '<span class="'+color+' tooltip" title="'+tip+'">'+index.name[1]+' &bull; '+index.value[1]+' : '+index.mtd_return[1]+'&#37</span>';
						
						/*ADD HTML to ticker_data*/
						ticker_data += index_data;	
					  });
					
					/*Render Ticker HTML on the page*/
					$status_box.html(ticker_data);
					
					/*apply tip JS*/
					$status_box.children('.tooltip').paraTip();
			   }
			 });
			
		 setTimer('tickerData()', 600000)
		}
	}
	
	function setTimer(func, time) {
		var t=setTimeout(func,time);
	}


/*### Plugins ###*/
/*-----------------------------------------------------------------------------*/ 
	/*For Rollover functions Changes made to increase speed and allow for HTML  insertion.
	Note -- Should use something other than the title tag to hold tool tip data.
	
	/*
	 * jQuery Plugin : paraTip
	 * by Paul Paradise
	 * http://www.paulparadise.co.uk
	 * Licensed Under GPL version 2 license.
	 */
	 
(function($){

    jQuery.fn.paraTip = function () {
       
        // append a div to the body
        var $tooltip = $('<div class="paraTip"></div>').appendTo('body');
       
        return this.each (function () {
			
			$this_item = $(this)
			
            // get the title and alt values
            var originalTitle = $this_item.attr('title');
            var originalAlt = $this_item.attr('alt');

            var positionToolTip = function(event)
            {
                // get the position
                var tPosX = event.pageX + 15;
                var tPosY = event.pageY + 2;
               
                // update the css
                $tooltip.css({top : tPosY, left: tPosX});
            }

            var showToolTip = function(event)
            {
                $this = $(this)
				// set the title and alt tags to be empty
                $this.attr('title', '').attr('alt', '').css("text-decoration","underline");
               
                // set the title tag to be the tool tip texts
                $tooltip.html(originalTitle).show();
               
                // position tool tip
                positionToolTip(event);
            }

            var hideToolTip = function()
            {
				$this = $(this)
                // reset the title and alt tag to original on hide
                $this.attr('title', originalTitle).attr('alt', originalAlt);
			 	$this.css("text-decoration","")
                // hide tool tip
                $tooltip.hide();
            }

            $this_item.hover(showToolTip, hideToolTip).mousemove(positionToolTip);
        });
    }
   
})(jQuery);

/*-----------------------------------------------------------------------------*/ 
/* News Feed for the Home Page
/*-----------------------------------------------------------------------------*/
/*
  - AKH1
  - Date: September 21, 2011
  - Version:1.0
  - Description: Pulls static XML files and display the most recent 6 news items on the home page. 
  - Changes: -- 
*/ 

/*Create object*/
function newsFeed (call, div, len) {
	this.xmlItems = $([]);
	this.len = len;
	this.call = call;
	this.div = div;
}

/*Apply methods*/
newsFeed.prototype = {
	callXmlData: function (xml){
		  var $theTable = $(_n.table),
			  url_path = "../src/xml/"+xml;
			    
			  $.ajax({
				type: "GET",
				url: url_path,
				dataType: "xml",
				async: false,
				cache: false,
				success: function (xml) {
					/*Loop through each item*/					
					$(xml).find('item').each(function(index){
						/*Check if we are over the "len" property*/						
						if (index<_n.len){
						   var $this = $(this);
							_n.xmlItems = _n.xmlItems.add(this);
							}
									
						});
				  }});
	},
			
	callLoop: function (){
		for (i in _n.call) {
			_n.callXmlData(_n.call[i]);
		}	
	},	
	
	sortNews: function () {
		_n.xmlItems.sort(function(a, b) {
		  var dateA = new Date($(a).find('pubDate').text()).valueOf(), 
			  dateB = new Date($(b).find('pubDate').text()).valueOf();
		  return dateB - dateA;
		  });
	},
	
	renderNews: function () {
		 var $div=$(_n.div);
		 /*Remove Loading message*/
  		 $('p.loading', $div).remove();
		 
		 _n.xmlItems.each(function(index){
			if (index <= _n.len) {
			   $this = $(this);
			  
			   var cat = $this.find('category').text(),
				   dat = $this.find('pubDate').text(),
				   title = $this.find('title').text(),
				   desc = $this.find('desc').text(),
				   linky = $this.find('link').text();
			  			   
			    //var content = '<p><span class="grey">'+cat+': '+dateConversion(dat, 'short')+'</span><br/><a href="'+linky+'">'+stringConcat(40, title, 'strip')+'</a></p>';
				
				var content = '<p><span class="grey">'+dateConversion(dat, 'euro')+'</span><br/><a href="'+linky+'">'+stringConcat(40, title, 'strip')+'</a><br/><span>'+stringConcat(78, desc, 'strip')+'</span></p>';
				
				if (index < _n.len) {
					$div.append(content); 
				} else if (index==_n.len){
					$div.append("<p style='text-align:left'><a class='read_more_bulletin' href='/s/home/index.shtml'><span id='arrowKnock2'><!-- dbl white on red arrow --></span>Login to Read More</a></p>")
				}
			}
		  });
	},
	
	init: function (){
		_n =  this;
		_n.callLoop();
		_n.sortNews();
		_n.renderNews();
	}
}
