// Verified: 2009-10-20 17:31

/**
 * Definition of global variables:
 *
 * @global      reURL       <RegExp>    This regular expression parse URL strings, it comes from the jQuery.url plugin strict mode validation
 * @global      url         <String>    This is the current window URL
 * @global      url_parts   <Array>     This is the matched URL parts of the current window URL using the jQuery.url strict regular expression
 * @global      cp          <JSON>      Enforce path=/ (VERY IMPORTANT) and 30 days expire setting
 */
var reURL=/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
	url=window.location.href||'',
	url_parts=reURL.exec(url)||[],
	cp={path:'/',expires:30};

// ; path=/
// jquery.cookie
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){var expires='',date;options=options||{};if(value===null){value='';options.expires=-1;}if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000));}else{date=options.expires;}expires='; expires='+date.toUTCString();}var path=options.path?'; path='+(options.path):'',domain=options.domain?'; domain='+(options.domain):'',secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');}else{var cookieValue=null,i,cookie,cookies;if(document.cookie&&document.cookie!=''){cookies=document.cookie.split(';');for(i=0;i<cookies.length;i++){cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}return cookieValue;}};

/**
 * Attach the parent class to the first immediate next item (if no other parent are found in between),
 * when the parent is click slide toggle the children next item.
 *
 * @param       parentClass <String>    Parent item CSS class name
 * @param       nextClass   <String>    Next immediate item CSS class name
 *
 * @variable    p           <jQuery>    The jQuery iterator over the parent selector
 * @variable    n           <jQuery>    The jQuery iterator over the immediate next element being iterated in DOM order.
 * @variable    m           <jQuery>    The jQuery iterator over all the menu container div that could be opened or closed.
 * @variable    v           <jQuery>    The jQuery iterator over all items to be hidden after the animation is completed.
 *
 * a) Find each parent item to be binded to
 * b) Iterate over them
 * c) Save the parent pointer into p
 * d) Start with next pointer of the parent into n
 * e) Verify that the next item actually exist
 * f) If it exists, verify if it is of class nextClass, if so bind the onclick handler on the parent targeting its children and stop searching
 *    else verify if it is of class parentClass, if so then stop searching.
 * g) If the parent has the select class then show the next pointer element
 *
 * h) Instead of only showing that pointer element, we want to toggle all the other visible menu containers that are not itself or one of it's parent
 *    then we ensure that the element to be shown is added to the animation queue.
 *
 * Notice: Use the fact that the first element [0] is null if nothing matched, since jQuery returns [] instead for chaining capability.
 */
function menu_accordion(parentClass, nextClass)
{
	$('a.'+parentClass).each(function(){

		var p=$(this),
			n=p,
			D='div.smenu,div.tmenu',
			VV=':visible',
			m=$('#menu').find(D),
			v;

		while((n=n.next()) && n[0])
		{
			if(n.hasClass(nextClass))
			{
				if(p.hasClass('select'))
					n.show();

				p.click(function(){
					if(p.attr('href').substr(0,1).toLowerCase()=='h')
					{
						//console.log('Parent is a link',p,n,v);
						return true;
					}
					else if(p.hasClass('goto'))
					{
						//if(!p.next(D).is(VV)) window.location.href=p.attr('ohref');
					}
					v=m.filter(VV).not(n.parents('div'));
					p.attr('visible',n.filter(VV).length);
					separation_height(n,v);
					v.add(n).animate({height:'toggle'},{queue:false,duration:'slow'});
				});
				return;
			}

			if(n.hasClass(parentClass))
				break;
		}
	});
}

/**
 * This function compare the heighest height between the content and the menu and ajust the seperation line witdh the right height.
 *
 * @param       r           <jQuery>    Items height to be removed
 * @param       a           <jQuery>    Items height to be added
 *
 * @return The target size of the menu (after the animation) in pixels
 */
function getMenuHeight(r, a)
{
	var m=$('#menu'),
		h;

	// Show/Hide to reflect the 'end' state.
	if(r)r.show();
	if(a)a.hide();

	// Take the height at that state.
	h=m.height();

	// Rollback to the previous 'start' state, so the animation can take place.
	if(r)r.hide();
	if(a)a.show();

	// Ensure it's an integer
	return parseInt(h, 10);
}

/**
 * This function compare the heighest height between the content and the menu and ajust the seperation line witdh the right height.
 *
 * @param       r           <jQuery>    DEFINED if you want an animation _AND_ to remove the height from it while toggling, FALSE to be set immediately
 * @param       a           <jQuery>    DEFINED and height to be shown after toggling it
 *
 * @variable    menu_h      <Integer>   The menu    height in pixels
 * @variable    cont_h      <Integer>   The content height in pixels
 * @variable    hh          <Integer>   The highest height in pixels
 *
 * @variable    b           <jQuery>    The jQuery iterator over the menu border middle to be animated or set
 * @variable    c           <JSON>      The CSS properties to be animated or set
 */
function separation_height(r, a)
{
	var menu_h  = getMenuHeight(r, a),
		cont_h  = parseInt($('#content').height(),10),
		hh      = (menu_h > cont_h) ? menu_h : cont_h,
		b       = $('#menu_border_mid'),
		c;

		// Prevent from being negative
		hh      = (hh <= 100) ? 0 : hh-80;
		c       = {height:hh};

		r ? b.animate(c, {queue:false,duration:'slow'}) : b.css(c);

		return hh;
}

/**
 * Load a Flash Video clip
 *
 * @param       path        <String>    The path prefix to the base_url         (REQUIRED, should be base_url() or base_url_clip())
 * @param       url         <String>    The URL to the clip                     (REQUIRED)
 * @param       flashvars   <JSON>      The default flashvars to be overridden  (FACULTATIVE, default to {})
 *
 * @variable    w           <Integer>   The video width
 * @variable    h           <Integer>   The video height
 *
 * @variable    p           <JSON>      Parameters for SWFObject
 * @variable    a           <JSON>      Attributes for SWFObject
 * @variable    f           <JSON>      Flash vars for SWFObject
 *
 * @return undefined
 */
function loadVideo(path, url, flashvars)
{
	var w=735,
		h=390,
		p={
			menu:'false',
			allowfullscreen:'true',
			allowscriptaccess:'always'
		},
		a={
			id:'vid'
		},
		f=flashvars||{};


	f.LocalPlayer    = (url.substr(0,4) != 'http');
	f.width          = w;
	f.height         = h-30;
	f.controlsColor  = 0x3c7384;
	f.controlerColor = 0xdedede;
	f.contrastValue  = 30;
	f.production     = true;
	if(url)f.URL     = url;
	swfobject.embedSWF(path+'/player/blue_player_091004.swf', 'videoplayer', w, h, '9.0.28', path+'/player/expressInstall.swf', f, p, a);
	//http://manulifeincomeplus.ca/_media/_common/flash/blueloader.swf
}

/**
 * This function cleans the URL by:
 *  - converting them to lowercase
 *  - removing the server host and http prefix
 *  - converting double slashes or backslashes to slash
 *  - removing any query strings or hash suffix
 *  - removing any non-alphanumeric parts (including dash and underscore)
 *
 * @param  url          <String>    The URL to be cleaned
 *
 * @return <String> The cleaned URL or an empty string
 */
function cleanURL(url){
	return url ?
			url.toLowerCase()
				.replace(/\s*([a-z]+\:)\/\/([a-z0-9\-\_\.\:]+)/ig,'')
				.replace(/[\\\/]+/g,'/')
				.replace(/\s*[#?&]+.*/g,'')
				.replace(/[^a-z0-9\/\-\_\.\:]+/ig,'')
				.replace(/[\\\/]+$/g,'')
				.replace(/^[\\\/]+/g,'')
			:'';
}

/**
 * This function automatically close all the menus except the current folder tree which is then reopened.
 *
 * NOTICE: The menus by default are all visible and opened so that the site can be navigated properly for users that have JavaScript disabled.
 *
 * - Retrieve the folder and file, folder only or file only (in that order) until one of them is not undefined
 * - Create an empty jQuery set
 * - Find all the folder body and close them all
 * - If the current path is defined and not the index path '/'
 *   then search for all links that:
 *      - have an a.href defined
 *      - does not start explicitly by javascript:
 *      - does not ends explicitly by #
 *      - matches the current cleaned path case-insensitively
 *      - if so, add them to the result set.
 *
 * - If the result set is less then 2 in size (to avoid that all folders are opened)
 *   then get the proper div menu container parents and open them
 *
 * @param       url         <String>        The URL to be used instead of the current window.location.href file path part
 *
 * @variable    p           <Array>         Local alias for url_parts global variable.
 * @variable    u           <String>        The URL parts which contains the folder/file path to be opened, if defined then it's cleaned.
 * @variable    r           <jQuery>        An empty jQuery iterator set by default, where new links will be added to it.
 * @variable    m           <jQuery>        A jQuery iterator over the #menu DOM element itself
 *
 * @constant    D           <String>        The CSS node/class selector set of menu containers to be closed or opened.
 *
 * @return undefined
 */
function fixMenu(url)
{
	$('#container').removeClass('js');
	var p=url_parts,
		u=url||p[9]||p[10]||p[11],
		r=$([]),
		D='div.tmenu,div.smenu',
		H='href',
		OH='o'+H,
		m=$('#menu').find(D).hide().end();

	if(u)
	{
		// Clean the window URL to be matched against
		u=cleanURL(u);

		// Avoid handling '/' use case
		if(u.length > 1)
		{
			/**
			 * This inner closure iterates over all links to find proper matching candidates
			 *
			 * @param    j      <Integer>       The current loop number
			 * @param    n      <DOMElement>    The current <A> DOM element to be iterated over
			 * @variable h      <String>        The current href value (Fake undefined parameter to avoid a var declaration)
			 */
			m.find('a').each(function(j,n,h){

				/**
				 * NOTICE:  The order of the AND close validation is important to avoid JavaScript and logical errors,
				 *          so we first test for undefined,
				 *          then for javascript: and #
				 *          then we clean it (so that the #offset is now cleared)
				 *          then we check if we found a match or not
				 *
				 *          If so, add it to the result set
				 */
				if((h=n.href) && !/(^[jJ])|(#$)/.test(h) && cleanURL(h).indexOf(u) >= 0) r = r.add(n);
			});

			/**
			 * Especially for fourth level menu, recursively substract virtual directory path until you find a match or you end up with /
			 */
			if(r.length<1)
			{
				u=u.replace(/[\\\/]+[^\\\/]+$/g,'/');
				if(u.length>1)return fixMenu(u);
			}
			else

			/**
			 * Found less than 3 matching links so explicitly show its DIV menu container parents that were previously hidden
			 *
			 * e.g.: /product_overview/ matches/ against /product_overvie/ and /product_overview_video/ links
			 * but   /, /index, /index.php, /index.php/application, /index.php/application/ might match everything...
			 * so keep this value reasonable.
			 *
			 * In any case, always choose the first one only
			 */
			if (r.length < 3)
			{
				if(r.hasClass('goto'))
				{
					r.attr(OH,r.attr(H)).attr(H,'#');
					r=r.next(D).find('a');
				}
				r=$(r[0]).parents(D).show();
			}
		}
	}
}

/**
 * Look-up for a cookie, returns true if already set, else set it to true for 30 days.
 *
 * @param       n           <String>    Name of the cookie to be set and verified
 * @variable    v           <String>    Value of the cookie to be retrieved
 *
 * @global      cp          <JSON>      Cookie settings
 *
 * @return <Boolean>    false if not found, true otherwise.
 */
function lookCookie(n)
{
	var v = $.cookie(n);

	if(!v)
		$.cookie(n,true,cp);

	// Ensure the value is true or false, using double boolean negation trick
	return !!v;
}

/**
 * Verify if this is the first visit for the home page either with the French or English URL
 *
 * @global      url         <String>    Alias for window.location.href, the current page URL
 * @variable    ev          <String>    The matched string against the English HOME URL or null if not found
 * @variable    fv          <String>    The matched string against the French  Accueil URL or null if not found
 *
 * @return undefined
 */
function firstVisit()
{
		// NOTICE: This also match /home/video after redirection, but the cookie will be already set.
	var ev = url.match(/(\/home)/i),
		fv = url.match(/(\/accueil)/i);

	// Matched against one of the home page, so set first visit CSS class to the body
	if(ev|fv) $('#body').addClass('fv');

	if(ev) splashvideo('firsten', '/home/video');
	if(fv) splashvideo('firstfr', '/accueil/video');
}

/**
 * Display a splash video by redirecting to the specified URL,
 * upon the first visit of that section only.
 *
 * @param       section     <String>    Name of the section, which is the name of that cookie
 * @param       url         <String>    The splash video URL to be redirected to
 * @param       id          <String>    The ID of the callee menu tag
 *
 * @variable    b           <Boolean>   Verify that this section is a first visit, if so, redirect.
 *
 * @return undefined
 */
function splashvideo(section, url, id)
{
	var b = lookCookie(section),
		v = 0;
	if(!b)
	{
		if(id) v = parseInt($('#'+id).attr('visible'),10);

		if(v < 1) window.location.href = url;
	}
}

/**
 * When the DOM is ready, execute these functions in order
 */
function loader()
{
	// Change links from # into javascript:void(0);
	firstVisit();

	// Must be called BEFORE menu_accordion, so that the current '.goto' link is toggled out
	fixMenu();

	fadeManager();

	$("a[href='#']").attr('href','javascript:void(0);');

	// Attach the parent class to its immediate next item of that kind for toggling purposes.
	menu_accordion('fmenu',      'smenu');
	menu_accordion('smenu_link', 'tmenu');

	separation_height();

	// typeof() operator has precedence over logical comparison operators, so parenthesis grouping is not needed.
	// The 3rd parameter explicitly defaults to {}, so it's not needed here.
	if(typeof video != 'undefined')
		loadVideo(base_clip_url, video);
}

/**
 * Bind DOM ready to this loader function
 */
$(loader);


/**
 * Fade in / fade out, the text associated with the designated #fadebox img,
 * since $.stop() does not work properly when multiple text fields are present,
 * we hide all other DIVs that should normally be animated, instead we copy over
 * the HTML content into the P element of the #fadeanim and animate that one instead by:
 *  - first fadeOut fast the current text
 *  - When the fadeOut animation is completed:
 *      - replace the existing text
 *      - fadeIn slowly the newly inserted text
 *
 * The animation occurs only on mouse enter, so that the person can read the image description,
 * even if she leaves the IMG container.
 *
 * @variable re             <RegExp>    Matches integer id
 * @variable fa             <jQuery>    The jQuery iterator over the #fadeanim DIV element
 * @variable fap            <jQuery>    The jQuery iterator over the #fadeanim DIV > P element
 * @variable id             <String>    The DOM element ID of the caller IMG element
 * @variable i              <Integer>   The numerical value contained inside the IMG element id string
 *
 * @global   g_fadeCount    <Integer>   The number of fade animation currently occurring
 * @global   g_fadeOrig     <String>    The original HTML text to be put back
 *
 * @global   g_timerId      <Integer>   The ID of the current mouseleave timerID for timeout
 * @global   g_delay        <Integer>   The number of millisecond for the mouseleave timeout
 *
 * @return undefined
 */
var g_fadeCount=0,g_fadeOrig,g_timerId=0,g_delay=0;
function fadeManager(){
	if($('#fadeevent')[0]){
		var re=/[0-9]+/,
			fa=$('#fadeanim'),
			img=$('#fadeevent img'),
			fap=fa.find('p');

		g_fadeOrig=fap.html();
		$('#fadebox div').not(fa).hide();
		img.mouseenter(function(){
				if(g_timerId>0){clearTimeout(g_timerId);g_timerId=0;}
				var me=$(this),
					id=me.attr('id')||0,
					i=re.exec(id)||0;

				me.fadeTo(100,0.6);

				if(g_fadeCount>0)
				{
					img.stop(true,true);
					fap.stop(true,true);
				}

				g_fadeCount++;
				fap.fadeOut('fast',function(){
					fap.html($('#fadebox'+i+' p').html()).fadeIn('slow',function(){
						if(--g_fadeCount<0)
							g_fadeCount=0;
					});
				});

		}).mouseleave(function(){
				if(g_timerId>0){clearTimeout(g_timerId);g_timerId=0;}
				img.stop(true,true);
				$(this).fadeTo(100,1);
				fap.stop(true,true);
				if(g_delay>0)
				g_timerId=setTimeout(function(){fap.html(g_fadeOrig);},g_delay);
				else fap.html(g_fadeOrig);
		});
	}
}
$(function(){if(document.all&&document.execCommand&&!window.opera)try{document.execCommand("BackgroundImageCache",false,true);}catch(err){}});
