/**
 * Main CW js file
 * Use this file for for implementing library code (jQuery plugins and the like)
 * Custom plugins or scripts should go in an separate, appropriately named file (eg search.js)
 * If it gets unmanageable, create separate files for each implementation
 */

$jq = jQuery.noConflict();

var CWTpl = function() {
	return {
		needCufon : function()
        {
            /*
            if (!fontInstalled()) { return true; }

            if ($jq.browser.msie && $jq.browser.version == '6.0') { return false; }
            */
            return true;
        },
		prepareShareMenu : function(namespace)
        {
            var over_menu = false;
            var over_menu_link = false;

            var share = $jq('#'+namespace+'ShareMenu');
            var share_link = $jq('#'+namespace+'ShareMenuLink');

            // share menu popup and hide
            share_link.mouseover(function() {
            // calculate position based on edge of share menu link
            var share_top = share_link.position().top  + share_link.innerHeight();
            var share_left = share_link.position().left;

            share.css('top', share_top);
            share.css('left', share_left);

            // hack to cope with IE 6.0 being strange about position: absolute
            if ($jq.browser.msie && $jq.browser.version == '6.0') {
              if (namespace == '') {
                share.css('left', 677);
              } else {
                share.css('left', 754);
              }
            }

            share.show();

            share_link.addClass('hover');

            over_menu_link = true;
            });

            share_link.mouseout(function() {
            if (!over_menu) {
              share.hide();
              share_link.removeClass('hover');
            }

            over_menu_link = false;
            });

            share.mouseover(function() {
            share.show();
            share_link.addClass('hover');
            if (CWTpl.needCufon()){
              Cufon.replace('#'+namespace+'PageControls a', {hover: true});
            }
            over_menu = true;
            });

            share.mouseout(function() {
            if (!over_menu_link) {
              share_link.removeClass('hover');
              // fix cufon, for some reasons it leave the replaced
              // text white, instead of reverting it to black
              if (CWTpl.needCufon()){
                Cufon.replace('#'+namespace+'PageControls a', {hover: true});
              }
              share.hide();
            }

            over_menu = false;
            });

            Cufon.replace('#'+namespace+'PageControls a', {hover: true});
		}
	};
}();

$jq(document).ready(function(){
	
	// display the header vertically aligned
	var container = $jq('#HeaderContainer');
	var header = $jq('#Header');
	
    // header.css('marginTop', (container.height() - header.height()) / 2);

	// check whether helvetica neue bold condensed is installed - HACK!
	function fontInstalled() {
		var el = $jq('<span>abcdefghijklmnopqrstuvwxyz</span>').hide().css({
			'font-weight': 'bold',
			'font-size': '20px',
			'text-transform': 'uppercase',
			'font-family': "'Helvetica Neue Bold Condensed', 'HelveticaNeueLT Com 77 BdCn'"
		}).appendTo('body');
		
		var w = el.width();
		
		el.remove();
		
		return (w > 270 && w < 280);
	}
    
	// set the active class on the menu item currently selected
	/*
	var pathname = window.location.pathname;
	
	$jq('#PrimaryNav a').each(function() {
		s = $jq(this);
		var pat = new RegExp(s.attr('href'));
		
		if (pat.test(pathname)) {
			s.addClass('active');
			console.log('here');
		}
	});
	*/

	// convert the tab divs to ui tabs
	if ($jq('#TabControls').length > 0) {
		content_tabs = $jq("#ContentTabs");
		content_tabs.tabs({
			show: function() {
				// fix bug that breaks what state the tabs revert to after
				// being un-hovered
				if (CWTpl.needCufon()){
					Cufon.replace('#TabControls a', {hover: true});
				}
				$jq.scrollTo('0%');
			}
		// handle #blah links on tabbed articles
		}).tabs('select', 'tab-'+unescape(self.document.location.hash.substring(1)));
		
		content_tabs.mouseout(function() {
			// fix bug that breaks what state the tabs revert to after
			// being un-hovered
			if (CWTpl.needCufon()){
				Cufon.replace('#TabControls a', {hover: true});				
			}
			
		});
	}
	
	$jq('#SiteSearchButton a').click(function() {
		$jq('#SearchForm_SearchForm').submit();
		
		return false;
	});
	
	// get rid of search text
	if ($jq('#SearchForm_SearchForm_Search').val() == 'Search') {
		$jq('#SearchForm_SearchForm_Search').val('');
	}
	
	if ($jq('#SearchForm_SideSearchForm_Search').val() == 'Search') {
		$jq('#SearchForm_SideSearchForm_Search').val('');
	}
	
	$jq("#rotating-items").carousel({direction: "horizontal", loop: true, pagination: true, autoSlide: true,effect: 'fade', autoSlideInterval: 5000, delayAutoSlide: 3000 });

    $jq.swapImage(".swapImage");

    $jq.scrollTo(".scrollTo");

    // do the font substitution if not ie6 without font - currently does it for all browsers
    // needCufon() always returns true
    if (CWTpl.needCufon()){
    //Cufon.replace('.font_substitution', {hover: true});
        Cufon.replace('#PrimaryNav a', {hover: true});
        Cufon.replace('#SecondaryNav a', {hover: true});
        Cufon.replace('#Menu2 a', {hover: true});
        Cufon.replace('#TabControls a', {hover: true});
        Cufon.replace('#PageControls a', {hover: true});
        Cufon.replace('a.page_colour_link', {hover: true});
        Cufon.replace('div.page_colour_link', {hover: true});
        Cufon.replace('span.page_colour_link', {hover: true});
        Cufon.replace('#CustomerLogin a');
        Cufon.replace('#SiteSearchButton a');
        Cufon.replace('#Header *');
        Cufon.replace('h1', {hover: true});
        Cufon.replace('h2');
        Cufon.replace('.font_substitution');
        Cufon.replace('.sectors_list li a', {hover: true});
        Cufon.replace('.product_list li a', {hover: true});
        Cufon.replace('#RightBar .page_colour_bullet', {hover: true});
    }
	// clear the search input box
	$jq('SearchForm_SearchForm_Search').attr('value', '');
	
	// display the header vertically aligned
    //	header.css('marginTop', (container.height() - header.height()) / 2);

	// background image popup
	// - disabled due to disagreement by website reviewers, despite early approval
    /*
	$jq('#BackgroundImageLink').hover(
		function() {
			var details = $jq('#BackgroundImageInfo');
			var bgPos = $jq('#Container').position();

			details.css('top', bgPos.top + 115);
			details.css('left', bgPos.left + 827);

			details.show();
		},
		function() {
			var details = $jq('#BackgroundImageInfo');
			details.hide();
		}
	);
    */
	// share menu popup
    CWTpl.prepareShareMenu('');
	
	// product column hover
	$jq('.column').hover(
		function() {
			s = $jq(this);
      //if (self.hasClass('blue_page')) { self.removeClass('blue_page'); self.addClass('blue_page_reverse'); }
		},
		function() {
			s = $jq(this);
      //if (self.hasClass('blue_page_reverse')) { self.removeClass('blue_page_reverse'); self.addClass('blue_page'); }
		}
	);

	// product details hover
	$jq('.product').hover(
		function(event) {
			var popup = $jq('#'+$jq(this).attr('id')+'-detail');
			popup.css('top', event.pageY - popup.innerHeight());
			popup.css('left', event.pageX + 5);
			// setup mouse tracking
			$jq().mousemove(function(e){
				popup.css('top', e.pageY - popup.innerHeight() - 5);
				popup.css('left', e.pageX + 5);
			}); 
			popup.show();
		},
		function(event) {
			var popup = $jq('#'+$jq(this).attr('id')+'-detail');
			// cancel the mouse tracking
			$jq().unbind('mousemove');
			popup.hide();
		}
	);
	
	// dialog popup
	var dialog = $jq("#Dialog").eq(0);
	
	$jq('.popup').click(function() {
		// blank the current dialog and load the new content
		// dialog.empty();
		dialog.dialog("destroy");
		$jq.get(this.href, function(data) {
			// set the data
			// - will also check here if it's a full page
			// - note, this line breaks IE6 using multiple IEs
			var content = $jq(data).find('#Content');
			//var content = $jq(data).find('#Layout');
			if (content.length > 0) {
				// full page content, get just what we need
				var page_colour = $jq(data).find('#Layout').eq(0).attr('class');
				page_colour = page_colour.replace(/sidebar_container/, '');

                var page_content = content.html();

				page_content = page_content.replace(/id="PageControls"/, 'id="PopupPageControls"');
				page_content = page_content.replace(/id="ShareMenuLink"/, 'id="PopupShareMenuLink"');
				page_content = page_content.replace(/id="ShareMenu"/, 'id="PopupShareMenu"');

                // IE6 weirdness: previous replaces don't work
				page_content = page_content.replace(/id=PageControls/, 'id="PopupPageControls"');
				page_content = page_content.replace(/id=ShareMenuLink/, 'id="PopupShareMenuLink"');
				page_content = page_content.replace(/id=ShareMenu/, 'id="PopupShareMenu"');

				dialog.html('<div id="OverlayContainer" class="'+page_colour+'"><div id="OverlayContent">'+page_content+'</div></div>');
			} else {
				dialog.html(data);
				var page_colour = $jq(data).filter('#OverlayContainer').eq(0).attr('class');
			}
			
			if (page_colour == '') {
				page_colour = 'white_page';
			}
			
			// trigger any font-substitution in the popup content
			Cufon.refresh();

			// this next bit of code is to get around the dialog not having the loaded
			// content included in it's style representation - despite being considered
			// in the DOM
			var timeout = null;
			dialog.dialog({
				bgiframe: true,
				autoOpen: false,
				width: 'auto',
				focus: function() {
					if (timeout == null) {
						timeout = setTimeout(function() {
							// grab the page colour of the popup to set the close (which is
							// outside the dialog) colour							
							if (page_colour) {
								$jq('.ui-dialog-titlebar').addClass(page_colour);
							}
							
							// make the background opaque
							$jq(".ui-widget-overlay").css('opacity', 0.9).css('height');
							
							// position it
							if ($jq.browser.msie && $jq.browser.version == '6.0') {
								// IE - safer to put it here
								dialog.dialog('option', 'position', [0, 0]).dialog('moveToTop');
							} else {
								dialog.dialog('option', 'position', ['center', 44]).dialog('moveToTop');
							}
							$jq(window).resize();

                            CWTpl.prepareShareMenu('Popup');
						}, 100)
					}
				},
                close: function(event, ui) {
                    $jq('#Dialog').empty();
                    return false;
                },
                modal: true,
                // off screen, we move it later
                position: [-10000, -10000]
            }).dialog('open');
			
		});

		return false;
	});
	
	// li backgrounds on various homepages
	$jq('#investors li, #issues li, .resource_link, .contact_col_text li').hover(
		function() {
			$jq(this).toggleClass('hover')
		},
		function() {
			$jq(this).toggleClass('hover')
		}
	);
	// click links
	$jq('#investors li, #issues li, .resource_link, .contact_col_text li').click(function(evt) {
		var a = $jq(evt.target).find('a').andSelf();
		
		if (a) {
			document.location = a.attr('href');
			return false;
		}
	});
	
	// mailto links
	$jq('a[href^=mailto]').addClass('contact_link');

	// bottom content
	var max_height = 0;
	var max_outer_height = 0;
	$jq('div.BottomContentLinks, div.BottomContentResources').each(function() {
		if ($jq(this).height() > max_height) {
			max_height = $jq(this).height();
		}
		if ($jq(this).outerHeight() > max_outer_height) {
			max_outer_height = $jq(this).outerHeight();
		}
	});
	
	$jq('div.BottomContentLinks').css({'height': max_height, 'min-height': max_height});
	$jq('div.BottomContentResources').css({'height': max_outer_height, 'min-height': max_outer_height});
	
    var vidPlayer;
    var vidClip;
    var vidRtmp;
    $jq('.video_popup').click(function() {
        var rel = $jq(this).attr('rel');
        var relparts = rel.split('||');
        var width = relparts[1];
        var height = relparts[2];
        var urlparts = relparts[0].split('/');
        var clip = urlparts.pop();
        var clipparts = clip.split('.');
        vidClip = clipparts[0];
        vidRtmp = urlparts.join('/');

        if (clipparts[1] != 'flv') {
            vidClip = clipparts[1] + ':' + vidClip;
        }
        
        dialog.dialog('destroy');
        dialog.html('<div id="OverlayContainer" style="height:' + height + 'px;width:' + width + 'px;"><div id="OverlayContent">&nbsp;</div></div>');
        dialog.dialog({
            bgiframe: true,
            autoOpen: false,
            width: 'auto',
            modal: true,
            open: function(event, ui) {
                if (vidClip == null) return true;
                
                $jq('.ui-dialog-titlebar').addClass('white_page');

                vidPlayer = $f('OverlayContainer', 'http://cwworldwide.com/corp_website/javascript/flowplayer-3.1.5.swf', {
                    clip: {
                        url: vidClip,
                        provider: 'influxis'
                    },
                    plugins: {
                        influxis: {
                            url: 'flowplayer.rtmp-3.1.3.swf',
                            netConnectionUrl: vidRtmp
                        }
                    }
                });

                vidPlayer.load();
            },
            close: function(event, ui) {
                if (vidPlayer == null) return false;
                // vidPlayer.unload();
                vidPlayer = null;
                vidClip = null;
                vidRtmp = null;
                $jq('#Dialog').empty();
                return false;
            }
        }).dialog('open');
        return false;
    });
});

function PrintPage() {
	window.print();
}
