/**
* Yara : main .js file
* ver : 0.1
*/

$(document).ready(function() {

    homePageFunctions();

	$('.navigation-tools ul li').mouseover(function() {
		$(this).toggleClass('hovered');
	}).mouseout(function() {
		$(this).toggleClass('hovered');
	});


	// Adding header on standard tables
	if ($('.standard-table').length) {
		$('.standard-table').each(function() {
			$(this).find('tr:first').addClass('header');
		});
	}

	$('#primary-content div.caption').each(function() {		
		var url = $(this).prev().attr('src');
		var pattern = /width=(\d+)/;
		var width = url.match(pattern)[1];
		
		if (!width) {
			width = $(this).prev().width();			
		}
		
		$(this).css('width', width + 'px');
		$(this).show();
	});

	if ($('#country-legal').length) {
		
		$('#country-legal-button').click(function() {
			var value = $('#country-legal').val();

			if (value >= 1 && value <= 6) {
				window.location = '/utilities/legal/not_accessible.aspx';
			}
			else if (value == 7) {
				window.location = '/utilities/legal/legal_info.aspx';
			}
		});
	}

	if (jQuery.browser.opera) {
		var bodyHeight = $('#page-body').height();
		$('.wrap').css('height', bodyHeight);
	}

    if ($('#UseCommunicationTool').length) {

        var substDropDown = $('#ctl00_ddPrimaryAreaOfUse');
        var prodDropDown = $('#ctl00_ddPrimaryAreaOfUse2');
        var breadCrumb = $('#breadcrumb li');
        var thispage = $('#breadcrumb li:last');

        $('.open-comment').click(function() {
            var id = $(this).attr('id');
            id = 'comment_' + id.substring(id.indexOf('_') + 1);

            var obj = document.getElementById(id);


            if ($(this).hasClass('opened')) {
                $(obj).slideUp();
                $(this).toggleClass('opened');
            }

            else {
                $(obj).slideDown();
                $(this).toggleClass('opened');
            }
        });

        $(substDropDown).change(function() {

            var searchField = $('#ctl00_txtSearch');
            var searchButton = $('#ctl00_btnSubstanceSearch');

            if ($(this).get(0).selectedIndex > 0) {

                if ($(searchField).hasClass('disabled')) {
                    $(searchField).toggleClass('disabled');
                }

                $(searchField).removeAttr('disabled');
                $('div.mandatory').hide();
                $(searchField).val('Type substance name here');
                $(searchField).select();
            }
            else {
                $(searchField).val('');
                $(searchField).toggleClass('disabled');
                $(searchField).attr('disabled', 'disabled');
                $(searchButton).attr('disabled', 'disabled');
                $('div.mandatory').show();
            }

            $('#ctl00_txtOtherName').val('');
            $('#ctl00_txtCAS').val('');
            $('#ctl00_txtEINECS').val('');
            $('#ctl00_txtProdTradenames').val('');
        });

        $(prodDropDown).change(function() {

            var searchField = $('#ctl00_txtProductSearch');
            var searchButton = $('#ctl00_btnSearch');

            if ($(this).get(0).selectedIndex > 0) {

                if ($(searchField).hasClass('disabled')) {
                    $(searchField).toggleClass('disabled');
                }

                $(searchField).removeAttr('disabled');
                $('div.mandatory').hide();
                $(searchField).val('Type product name here');
                $(searchField).select();
                $(searchButton).removeAttr('disabled');
            }
            else {
                $(searchField).val('');
                $(searchField).toggleClass('disabled');
                $(searchField).attr('disabled', 'disabled');
                $(searchButton).attr('disabled', 'disabled');
                $(searchField).val('');
                $('div.mandatory').show();
            }
        });

        $('#ctl00_txtSearch').focus(function() {
            $(this).select();
        });

        $('#ctl00_txtSearch').blur(function() {
            if ($(this).val() == '') {
                $(this).val('Type substance name here');
            }
        });
    }

	
	/* Loads Yara.com carousels */
	carousal();
	carousal1();
	
	/* Loads country site carousels */
    carouselWide();
	carouselNarrow();
	carouselOne();

    // Adds Yara local sites flyout
    localSites();
	
	// Adding 'Back to top' anchors
	backToTop();
    
	// Text-clearing for search box	
    $("#searchQuery :text").focus(function() {
        $(this).val('');
    });
	
	$("#SearchTxt :text").focus(function() {
        $(this).val('');
    });

    // Adds the 'first' class to the first menu option
    $("#access-navigation > li:first").addClass('first');

    // Adds the 'last' class to the last menu option
    $("#access-navigation >li:last").addClass('last');

    // Removes the underline from the menu option above the current option at level 1
    $("#access-navigation li.current:first").prev().children().addClass('noUnderline');

    // Removes and adds underlines from menu options hovered over
    $("#access-navigation li").hover(function() {
        $(this).prev().children().addClass('hideUnderline');
    }, function() {
        $(this).prev().children().removeClass('hideUnderline');
    });

    //implements side-bar tabnavs if they are present on the page
    tabnavs();
    ipf_tabnavs();

    newsBox_tabnavs();

    // Add hover effect for the carousal box
    boxhover();

    // Apply zebra stips to events-calander-table
    zebra('#events-calendar-table');

    // Show the regions box in which we operate
    ourRegions();

    // Activate the print button
    print_page()
	
	// Insert emailThisPage form
    createEmailForm();

    // Activate emailThisPage
    emailThisPage();

    // Table row highlighter when hovered over
    tableRowHover();

    // LoadFontSize();
    loadFontSize();
    fontSizeChanger();

	if (sIFR.bIsDisabled == false) {
		doSifrReplacements();
	}
		
	try
	{
		$("#QsearchQuery").keyup(function(e) { 
			if(e.keyCode == 13) { 
				ExecuteSearch();
			} 
		});
	}
	catch (e) {}
	
	// Yara-TV navigation menu juggler
	if ($('#smallNav').length) {		
		smallNavJuggler('#smallNavOption', '#firstLevelNav');
		
		$('#backToPrevPage').click(function(){
			history.go(-1);			
		});
	}
	
});

var smallNavJuggler = function(menuOptionID, smallMenuID) {
	$(menuOptionID).mouseover(function() { 
			$(smallMenuID).show();
			$(menuOptionID).addClass('active')
	});
	
	$(menuOptionID).mouseout(function() { 
			$(smallMenuID).hide();
			$(menuOptionID).removeClass('active');	
	});
	$(menuOptionID).click(function() {
		
	});
};


$.fn.wait = function(time, type) {
    time = time || 1000;
    type = type || "fx";
    return this.queue(type, function() {
        var self = this;
        setTimeout(function() {
            $(self).dequeue();
        }, time);
    });
};


var backToTop = function() {

	var viewport_height;
    
	if (self.innerheight) { // all except Explorer 
    	viewport_height = self.innerHeight;
    }
	
    else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode 
		viewport_height = document.documentElement.clientHeight; 
    }
	
    else if (document.body) { // other Explorers 
    	viewport_height = document.body.clientHeight; 
    } 

    var ttl = $('.back-to-top');

	if (ttl) {
    	if ($('#Form1').height() <= viewport_height) ttl.hide();
	}
	
};

var createEmailForm = function() {
    $('#page-body').append('<div id="emailThisPageForm"><div class="closeForm"><a href="#" id="emailCloseButton">Close X</a></div><iframe id="emailFormPage" src="/utilities/email.aspx" border="0" width="310px" height="450px" frameborder="0" scrolling="no"></iframe></div>');
}


var emailThisPage = function() {
    $("#utilities li.email a").click(function() {
        if ($("#emailThisPageForm").is(":hidden")) {
            $("#emailThisPageForm").slideDown("slow");
        } else {
            $("#emailThisPageForm").hide();
        }
        return false;
    });

    $("#emailThisPageForm .closeForm a").click(function() {
        closeEmailThisPageForm();
        return false;
    });
}

var closeEmailThisPageForm = function() {
    if ($("#emailThisPageForm").is(":visible")) {
        $("#emailThisPageForm").slideUp("slow");
    }
}

//highlights the table row hovered over 
var tableRowHover = function() {
    $('table:not(.documents) tr').hover(function() {
		$(this).addClass('hovered-row');
	}, function() {
		$(this).removeClass('hovered-row');		
    });
}

var ourRegions = function() {

    if ($('#where-we-operate').length) {
        $('#where-we-operate .region .link').click(function() {
            $('#where-we-operate li.on').removeClass('on');
            $('#where-we-operate li.region').removeAttr('style');
            $(this).parent().addClass('on').css('z-index', '99');
            var h = $('#where-we-operate .on div.sites-in-region').height();

            //console.log(h);
            h = Math.floor(h / 2) * -1;
            h = h + 7;
            c = h - 15;

            //h = (h > -50) ? 20 : h;
            //console.log('after:'+h);
            //h = h - 40;
            //c = h - 15;
            h = h + 'px';
            c = c + 'px';

            $('#where-we-operate .on div.sites-in-region').css('top', h);
            $('#where-we-operate .on .close-button').css('top', c);
            return false;
        });

        $('#where-we-operate .close-button').click(function() {
            $('#where-we-operate li.on').removeClass('on');
            $('#where-we-operate li.region').removeAttr('style');
            return false;
        });
    }
}

var zebra = function(id) {
    var str = "'" + id + ' tr:odd' + "'";
    $('#events-calendar-table tr:odd').addClass('highlighted');
    str = null;
}

var homePageFunctions = function() {

	var homePage = $("#home-page").length;
	
    if (homePage) {
        for (var i = 0; i < 20; i++) {
            var menuItem = document.getElementById("home-menu-" + i);

            if (menuItem != null) {
                flyerMaker("#home-menu-" + i, "#flyer-" + i);
                menuJuggler("#home-menu-" + i, "#flyer-" + i);
            }
        }
    }
	
	if (homePage && $('#country-home').length == 0) {
		insertHomeFlash();
	}
}

var newsBox_tabnavs = function() {

    if ($('#news-box').length) {
        var latestData = $('#news-box .latest');
        var mostreadData = $('#news-box .most-read');

        $('#news-box #tab-latest').click(function() {
            latestData.show();
            mostreadData.hide();
            $(this).addClass('current');
            $('#news-box #tab-most-read').removeClass('current');
            return false;
        });

        $('#news-box #tab-most-read').click(function() {
            latestData.hide();
            mostreadData.show();
            $(this).addClass('current');
            $('#news-box #tab-latest').removeClass('current');
            return false;
        });
    }
}

// Adds tabs functionality
var ipf_tabnavs = function() {
	
    if ($('.industrial-product-finder').length) {
        var searchbox = $('.ipf-search-box');
        var ipf_markets = $('.ipf-markets-list');
        var ipf_a2z = $('.ipf-a2z-list');

        $('#tab-ipf-search').click(function() {
            searchbox.show();
            $(this).addClass('current');
            ipf_markets.hide();
            $('#tab-ipf-market').removeClass('current');
            ipf_a2z.hide();
            $('#tab-ipf-a2z').removeClass('current');
            return false;
        });

        $('#tab-ipf-market').click(function() {
            searchbox.hide();
            $('#tab-ipf-search').removeClass('current');
            ipf_markets.show();
            $(this).addClass('current');
            ipf_a2z.hide();
            $('#tab-ipf-a2z').removeClass('current');
            return false;
        });

        $('#tab-ipf-a2z').click(function() {
            searchbox.hide();
            $('#tab-ipf-search').removeClass('current');
            ipf_markets.hide();
            $('#tab-ipf-market').removeClass('current');
            ipf_a2z.show();
            $(this).addClass('current');
            return false;
        });
    }
}

// Another version to add tabs functionality
var tabnavs = function() {

    var searchbox = $('.search-box');
    var tagcloud = $('.tags-cloud');
    var popular = $('.popular');

    $('#tab-search').click(function() {
        searchbox.show();
        $(this).addClass('current');
        popular.hide();
        $('#tab-popular').removeClass('current');
        tagcloud.hide();
        $('#tab-cloud').removeClass('current');
        return false;
    });

    $('#tab-popular').click(function() {
        searchbox.hide();
        $('#tab-search').removeClass('current');
        popular.show();
        $(this).addClass('current');

        tagcloud.hide();
        $('#tab-cloud').removeClass('current');
        return false;
    });

    $('#tab-cloud').click(function() {
        searchbox.hide();
        $('#tab-search').removeClass('current');
        popular.hide();
        $('#tab-popular').removeClass('current');
        tagcloud.show();
        $(this).addClass('current');
        return false;
    });
}

// Adds the flash movie on the home page. If addition is successful, it also adds 'has_HF' class name to the <html> element
var insertHomeFlash = function() {
    
	var flashvars = {};
    var params = { 'WMODE': "opaque" };
    var attributes = {};
    
	// This has a dereffered execution and hence no referrence return value
    swfobject.embedSWF("/swf/yara.swf", "flash-wallpaper", "987", "545", "8.0.0", 'false', flashvars, params, attributes);

    // This is queued for execution after swf has been inserted
    swfobject.addDomLoadEvent(function() {

		var swf = document.getElementById("flash-wallpaper");
        
		if (swf && swf.nodeName === "OBJECT") {
            $('html').addClass('has_HF');
        } 
		else {
            /* This condition will arise when the swf object was not created possibly becuase no flash player existed or
               JavaScript  was not available in either case it would be best to load the non-flash version of the page. */
            $('html').addClass('no_HF');
        }
    });
}

// Creates local sites green flyout 
var localSitesShow = false;

// Creates local sites green flyout 
var localSites = function() {

	/* Fix for IE6 */
	var breadcrumb = $('#breadcrumb');
	var outer = breadcrumb.html();
	var inner = breadcrumb.children('div:first').html();


    $('#yara-local-websites .c-button').click(function() {
        
		if (localSitesShow == false) {
			
			/* Fix for IE6 */
			breadcrumb.html(inner);	
            
			$('#local-sites').show();
            var n = $('#local-sites h4 object').length;
            
			if (sIFR.bIsDisabled == false && n < 1) {
					sIFR.replaceElement(named({
						sSelector:"#local-sites h4", 
						sFlashSrc:"/swf/yaramax_regular_latin1.swf", 
						sColor:"#ffffff;", 
						sBgColor:"#658d2d", 
						nPaddingTop:0, 
						nPaddingBottom:0, 
						nMarginTop:-15,
						sFlashVars:"textalign=left&offsetTop=0"
				}));
            }
            n = null;

            //for IE6 select box hiding
            if ($.browser.msie) {
                $('#content select').css('visibility', 'hidden');
            }
			
            localSitesShow = true;
        }
        else {
			/* Fix for IE6 */
			breadcrumb.html(outer);		
        
			$('#local-sites').hide();
            
			if ($.browser.msie) {
                //for IE6 select box unhiding 
                $('#content select').css('visibility', 'visible');
            }
			
            localSitesShow = false;
        }
    });

    // Hides the flyout on mouseout
    $('#local-sites').mouseout(function(e) {
    	if (localSitesShow && !IsWithinLocalSites(e)) {
			breadcrumb.html(outer);
            $('#local-sites').hide();
            if ($.browser.msie) {
                //for IE6? select box unhiding 
                $('#content select').css('visibility', 'visible');
            }
            localSitesShow = false;
        }
    });
}

// Mouseout/over is not reliable so we check if we're within the div tag
function IsWithinLocalSites(e) {
	
    var width = $('#local-sites').width();
    var height = $('#local-sites').height();
    var offset = $('#local-sites').offset();
    if (e.pageX > offset.left && e.pageX < (offset.left + width)
        && e.pageY > offset.top && e.pageY < (offset.top + height)) {
        return true;
    }
    return false;
}


/*
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
*/

$.fn.hoverIntent = function(f, g) {
    // default configuration options
    var cfg = {
        sensitivity: 7,
        interval: 50,
        timeout: 200
    };
    // override configuration options with user supplied object
    cfg = $.extend(cfg, g ? { over: f, out: g} : f);

    // instantiate variables
    // cX, cY = current X and Y position of mouse, updated by mousemove event
    // pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
    var cX, cY, pX, pY;

    // A private function for getting mouse position
    var track = function(ev) {
        cX = ev.pageX;
        cY = ev.pageY;
    };

    // A private function for comparing current and previous mouse position
    var compare = function(ev, ob) {
        ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
        // compare mouse positions to see if they've crossed the threshold
        if ((Math.abs(pX - cX) + Math.abs(pY - cY)) < cfg.sensitivity) {
            $(ob).unbind("mousemove", track);
            // set hoverIntent state to true (so mouseOut can be called)
            ob.hoverIntent_s = 1;
            return cfg.over.apply(ob, [ev]);
        } else {
            // set previous coordinates for next time
            pX = cX; pY = cY;
            // use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
            ob.hoverIntent_t = setTimeout(function() { compare(ev, ob); }, cfg.interval);
        }
    };

    // A private function for delaying the mouseOut function
    var delay = function(ev, ob) {
        ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
        ob.hoverIntent_s = 0;
        return cfg.out.apply(ob, [ev]);
    };

    // A private function for handling mouse 'hovering'
    var handleHover = function(e) {
        // next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
        var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
        while (p && p != this) { try { p = p.parentNode; } catch (e) { p = this; } }
        if (p == this) { return false; }

        // copy objects to be passed into t (required for event object to be passed in IE)
        var ev = jQuery.extend({}, e);
        var ob = this;

        // cancel hoverIntent timer if it exists
        if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

        // else e.type == "onmouseover"
        if (e.type == "mouseover") {
            // set "previous" X and Y position based on initial entry point
            pX = ev.pageX; pY = ev.pageY;
            // update "current" X and Y position based on mousemove
            $(ob).bind("mousemove", track);
            // start polling interval (self-calling timeout) to compare mouse coordinates over time
            if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout(function() { compare(ev, ob); }, cfg.interval); }
        
			if ($('.has_HF').length) {
            	//fade the flash backgorund
				var swf = document.getElementById("flash-wallpaper");
				if (swf) {
					
					try {
						swf.overlayEnDis(true);
					} 
					catch (err) { }					
				}
				swf = null;
			}
            // else e.type == "onmouseout"
        } 
		else {
            // unbind expensive mousemove event
            $(ob).unbind("mousemove", track);
            // if hoverIntent state is true, then call the mouseOut function after the specified delay
            if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout(function() { delay(ev, ob); }, cfg.timeout); }
			
			if ($('.has_HF').length) {
            	//brightens the earlier faded flash background     
				var swf = document.getElementById("flash-wallpaper");
				if (swf) {
					
					try {
						swf.overlayEnDis(false);
					} 
					catch (err) { }		
				}
				swf = null;
				// console.log('out if menu');
			}
        }
    };

    // bind the function to the two event listeners
    return this.mouseover(handleHover).mouseout(handleHover);
};

// adds hiding/unhiding feature to the left menu suboptions
var menuJuggler = function(menu_id, flyer_id) {
    $(menu_id).hoverIntent(function() {
        $(flyer_id).show();
        $(this).addClass("current");
		
		if (sIFR.bIsDisabled == false) {	
			var flashFlyoutTitle = flyer_id+" h2";
				sIFR.replaceElement(named({
						sSelector:flashFlyoutTitle, 
						sFlashSrc:"/swf/yaramax_regular_latin1.swf", 
						sColor:"#ffffff;", 
						sBgColor:"#658d2d", 
						nPaddingTop:0, 
						nPaddingBottom:0, 
						nMarginTop:-150,
						sFlashVars:"textalign=leftoffsetTop=0",
						sWmode:"opaque"}));
		}
	}, function() {
	    $(flyer_id).hide();
        $(this).removeClass('current');
    });
}


//create the flyout code for the left nav based onthe options available onthe primary-content of the page and inserts in under each left nav option
var flyerMaker = function(menu_id, flyer_id) {
    var str = '#home-page ' + menu_id;
    if ($(str)) {
        //clone the flyer div
        var flyer = $(flyer_id).clone();

        //remove the flyer from dom
        $(flyer_id).remove();

        // attach the flyer as submenu option under aboutus
        flyer.appendTo(menu_id);
    }
}


//applies overlay to the object specified
var applyOverlay = function(id) {
    //alert('Hi, did anyone call me! No? Doh!');
    $(id).prepend('<div id="overlay" />');
    $(id).css({ 'position': 'relative' }); //important or else the overlay will not fit well!

    $('#overlay').css({
        'width': '100%',
        'height': '100%',
        'z-index': '3',
        'position': 'absolute',
        'top': '0',
        'left': '0',
        'background-color': '#000'

    });

    if ($.browser.msie) {
        $('#overlay').css({
            'filter': 'alpha(opacity=80)'
        });
    }
    else {
        if ($.browser.mozilla) {
            $('#overlay').css({
                '-moz-opacity': '.80'
            });
        }
        else {
            $('#overlay').css({
                'opacity': '.80'
            });
        }
    }
}

var removeOverlay = function(id) {
    $('#overlay').remove();
}


var carousal = function() {

    if ($('.normalcarousal').length) {
        var boxes = 0;
        var slide_unit = 0;
        var toShow = 3;
        var box = 1;

        /*
        * Steps
        * 1. Get the width of the single box ( containing the slide including its margins)
        *    This box should not have any padding or margin, it should be neat width box.
        * 2. Find out number of boxes
        * 3. Get the style/s for the end of the list
        * 4. Engage the carousal
        */
        //console.log(box);

        if ($('#carousal').length) {

            boxes = $('.slider-belt li').length;
            var nwidth = (140 * boxes) + 'px'; //adjusts the width of the slider-belt, or else all the boxes will not show... only those fitting in the width showup

            $('.slider-belt').css('width', nwidth);

            // Getting the highlighted box' number in the carousel list.
            var active = getActiveBox();
            if (active > toShow) {
                $(".slider-belt").css({
                    "left": (-140 * (active - toShow)) + "px"
                });
                box = box * active - 2;
            }

			if (boxes >= toShow) {
				$('.status-counter').html(' ' + box + '-' + (box + 2) + ' of ' + boxes);
			}
			else {
				$('.status-counter').html(' ' + box + '-' + boxes + ' of ' + boxes);				
			}

            if (boxes > toShow) {

                $('.next').click(function() {

                    if (box < (boxes - toShow + 1)) {

                        $(".slider-belt").animate({

                            "left": "-=140px"
                        }, "medium");
                        box++;
                        $('.status-counter').html(' ' + box + '-' + (box + 2) + ' of ' + boxes);
                    }
                    else {
                        //alert('you are at last');
                    }
                });

                $('.previous').click(function() {
                    //   console.log(box);
                    if (box > 1) {
                        $(".slider-belt").animate({

                            "left": "+=140px"
                        }, "medium");
                        box--;
                        $('.status-counter').html(' ' + box + '-' + (box + 2) + ' of ' + boxes);
                    }
                });

            }
            // If there are three boxes or less in the carousel, the arrows and the status counter will be removed
            else {
                document.getElementById('carousal').className = 'three-or-less';
                
            }
        } //if$
    } //if
}


var carouselWide = function() {

    if ($('#carousel.wide').length) {
        var boxes = 0;
        var slide_unit = 0;
        var toShow = 3;
        var box = 1;

		boxes = $('.slider-belt li').length;
		var nwidth = (225 * boxes) + 'px';

		$('.slider-belt').css('width', nwidth);

		if (boxes > toShow) {

			$('.next').click(function() {

				if (box < (boxes - toShow + 1)) {

					$(".slider-belt").animate({

						"left": "-=225px"
					}, "medium");
					box++;
				}
				else {
					//alert('you are at last');
				}
			});

			$('.previous').click(function() {
				//   console.log(box);
				if (box > 1) {
					$(".slider-belt").animate({

						"left": "+=225px"
					}, "medium");
					box--;
				}
			});
		}
    }
}

var carouselNarrow = function() {

    if ($('#carousel.narrow').length) {
        var boxes = 0;
        var slide_unit = 0;
        var toShow = 3;
        var box = 1;

		boxes = $('.slider-belt li').length;
		var nwidth = (225 * boxes) + 'px';

		$('.slider-belt').css('width', nwidth);

		if (boxes > toShow) {

			$('.next').click(function() {

				if (box < (boxes - toShow + 1)) {

					$(".slider-belt").animate({

						"left": "-=225px"
					}, "medium");
					box++;
				}
				else {
					//alert('you are at last');
				}
			});

			$('.previous').click(function() {
				//   console.log(box);
				if (box > 1) {
					$(".slider-belt").animate({

						"left": "+=225px"
					}, "medium");
					box--;
				}
			});
		}
    }
}

var carouselOne = function() {

    if ($('.carousel-one').length) {
        var boxes = 0;
        var slide_unit = 0;
        var toShow = 1;
        var box = 1;

		boxes = $('.slider-belt .carousel-box').length;
		var nwidth = (470 * boxes) + 'px';

		$('.slider-belt').css('width', nwidth);

		if (boxes > toShow) {

			$('.next-arrow').click(function() {

				if (box < (boxes - toShow + 1)) {

					$(".slider-belt").animate({

						"left": "-=470px"
					}, "medium");
					box++;
				}
				else {
					//alert('you are at last');
				}
			});

			$('.previous-arrow').click(function() {
				//   console.log(box);
				if (box > 1) {
					$(".slider-belt").animate({

						"left": "+=470px"
					}, "medium");
					box--;
				}
			});
		}
    }
}


// Help function to get the highlighted box' number in the carousel list.
function getActiveBox() {
	
	$('#viewframe').find('li').each(function(i) {										 
		if ($(this).attr('class') == 'current') {
			return i + 1;
		}
	});
}


var carousal1 = function() {

    if ($('#carousal.wide').length) {

        var boxes = 0;
        var slide_unit = 0;
        var toShow = 3;
        var box = 1;

        /*
        * Steps
        * 1. Get the width of the single box ( containing the slide including its margins)
        *    This box should not have any padding or margin, it should be neat width box.
        * 2. Find out number of boxes
        * 3. Get the style/s for the end of the list
        * 4. Engage the carousal
        */
        //console.log(box);

        if ($('#carousal').length) {

            boxes = $('.slider-belt li').length;
            //alert($('.slider-belt li').length);

            var nwidth = (213 * boxes) + 'px'; //adjusts the width of the slider-belt, or else all the boxes will not show... only those fitting in the width showup

            $('.slider-belt').css('width', nwidth);
            $('.status-counter').html(' ' + box + '-' + (box + 2) + ' of ' + boxes);

            if (boxes > toShow) {

                $('.next').click(function() {

                    if (box < (boxes - toShow + 1)) {

                        $(".slider-belt").animate({
                            "left": "-=213px"

                        }, "medium");
                        box++;
                        $('.status-counter').html(' ' + box + '-' + (box + 2) + ' of ' + boxes);
                    }
                    else {
                        //alert('you are at last');
                    }
                });

                $('.previous').click(function() {
                    //   console.log(box);
                    if (box > 1) {
                        $(".slider-belt").animate({
                            "left": "+=213px"

                        }, "medium");
                        box--;
                        $('.status-counter').html(' ' + box + '-' + (box + 2) + ' of ' + boxes);
                    }
                });

            } //if(boxes

        } //if$
    } //if


}


var boxhover = function() {
    $('.box .box-text').hover(
		function() {
		    $(this).addClass('hovered')
		}, function() {
		    $(this).removeClass('hovered')
		}
	);
}


/* print function */
var print_page = function() {
    $('#utilities .print').click(function() {

        /* Support Variables */
        platform = navigator.platform; platform = platform.toLowerCase();
        var MAC = platform.indexOf('mac')
        var NS = (navigator.appName == "Netscape");
        var VERSION = parseInt(navigator.appVersion);

        if (navigator.appVersion.indexOf("Win") != -1) {
            window.print();
        } else if (MAC) {
            alert("You will have to use the print command from the file menu\n");
        } else if (NS) {
            window.print();
        } else if ((VERSION > 3) && (MAC < 0)) {
            var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
            document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
            WebBrowser1.ExecWB(6, 1); //Use a 1 vs. a 2 for a prompting dialog box
            //WebBrowser1.outerHTML = "";
        } else {
            alert("You will have to use the print command from the file menu\n");
        }

        return false;
    });
}

/* fontResizing functions */

/* loadFontSize()
* reads the FontSize cookie and sets the font size accordingly
*/

function loadFontSize() {
    //alert(document.cookie);
    //alert(readCookie('yaraFontSize'));
    var size;

    size = readCookie('yaraFontSize'); //read the size cookie
    if (size == null) {
        size = 0;
    }

    //alert( 'size'+size);
    setFontSize(size);
}

/* 
* function to handle the clicks on FontSize Changer (AAA) 
* - calls the function to change the class of the content container, according to selected option
* - calls the function to change the class of the AAA, according to selected option
*/



var fontSizeChanger = function() {

    $('#footer .text-resize a.x').click(function() {
        //alert('you chose x');
        setFontSize(0);
        createCookie('yaraFontSize', 0);
        return false;
    });

    $('#footer .text-resize a.xl').click(function() {
        //alert('you chose xl');
        setFontSize(1);
        createCookie('yaraFontSize', 1);
        return false;
    });


    $('#footer .text-resize a.xxl').click(function() {
        //alert('you chose xxl');
        setFontSize(2);
        createCookie('yaraFontSize', 2);
        return false;
    });

}


/*
* setFontSize()
* - changes the class of the content container, according to selected option
* - changes the class of the AAA, according to selected option and marks it current
*/

var setFontSize = function(size) {
    switch (size) {
        case 0:
        case "0":
            $('body').removeClass('zx zxl zxxl');
            $('body').addClass('zx');

            $('.text-resize *').removeClass('current');
            $('.text-resize .x').addClass('current');

            break;
        case 1:
        case "1":
            $('body').removeClass('zx zxl zxxl');
            $('body').addClass('zxl');

            $('.text-resize *').removeClass('current');
            $('.text-resize .xl').addClass('current');

            break;
        case 2:
        case "2":
            $('body').removeClass('zx zxl zxxl');
            $('body').addClass('zxxl');

            $('.text-resize *').removeClass('current');
            $('.text-resize .xxl').addClass('current');

            break;
    } //switch

}




/* 
* functions to create, read, erase cookies
* Ref : http://www.quirksmode.org/js/cookies.html
*/

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

var doSifrReplacements = function(){
	if(typeof sIFR == "function"){
	
	// This is the preferred "named argument" syntax
		sIFR.replaceElement(named({
						sSelector:"h2.content-title,.member-details h3.name", 
						sFlashSrc:"/swf/yaramax_regular_latin1.swf", 
						sColor:"#484848", 
						sLinkColor:"#484848", 
						sBgColor:"#FFFFFF", 
						sHoverColor:"#484848", 
						nPaddingTop:0, 
						nPaddingBottom:0, 
						sFlashVars:"textalign=left&offsetTop=0",
						sWmode:"opaque"
				}));
				


		sIFR.replaceElement(named({
						sSelector:".quote p", 
						sFlashSrc:"/swf/yaramax_regular_latin1.swf", 
						sColor:"#457900;", 
						sLinkColor:"#457900;", 
						sBgColor:"#FFFFFF", 
						sHoverColor:"#457900;", 
						nPaddingTop:0, 
						nPaddingBottom:0, 
						sFlashVars:"textalign=right&offsetTop=0",
						sWmode:"opaque"
				}));


		sIFR.replaceElement(named({
						sSelector:".head-line", 
						sFlashSrc:"/swf/yaramax_regular_latin1.swf", 
						sColor:"#ffffff;", 
						sLinkColor:"#ffffff;", 
						sHoverColor:"#ffffff;", 
						nPaddingTop:0, 
						nPaddingBottom:0, 
						sFlashVars:"textalign=right&offsetTop=0",
						sWmode:"transparent",
						kerning:"true"
				}));
		
		
		sIFR.replaceElement(named({
						sSelector:".sub-head-line", 
						sFlashSrc:"/swf/yaramax_regular_latin1.swf", 
						sColor:"#ffffff;", 
						sLinkColor:"#ffffff;", 
						sHoverColor:"#ffffff;", 
						nPaddingTop:0, 
						nPaddingBottom:0, 
						sFlashVars:"textalign=right&offsetTop=0",
						sWmode:"transparent",
						kerning:"true"
				}));
		
		
		sIFR.replaceElement(named({
						sSelector:".carousel-one .info p.header", 
						sFlashSrc:"/swf/yaramax_regular_latin1.swf", 
						sColor:"#ffffff;", 
						sLinkColor:"#ffffff;", 
						sHoverColor:"#ffffff;", 
						nPaddingTop:0, 
						nPaddingBottom:0, 
						sFlashVars:"textalign=left&offsetTop=0",
						sWmode:"transparent",
						kerning:"true"
				}));		

/*
		sIFR.replaceElement(named({
						sSelector:".flyer h2", 
						sFlashSrc:"/swf/yaramax_regular_latin1.swf", 
						sColor:"#ffffff;", 
						sBgColor:"#658d2d", 
						nPaddingTop:0, 
						nPaddingBottom:0, 
						nMarginTop:-15,
						sFlashVars:"textalign=right&offsetTop=0",
						sWmode:"transparent"
				}));


		
		
		sIFR.replaceElement(named({
						sSelector:".our-people-list .name", 
						sFlashSrc:"/swf/yaramax_regular_latin1.swf", 
						sColor:"#457900;", 
						sLinkColor:"#457900;", 
						sHoverColor:"#457900;", 
						nPaddingTop:0, 
						nPaddingBottom:0, 
						sFlashVars:"textalign=left&offsetTop=0",
						sWmode:"transparent"
				}));

		*/
	};
}; 

//################################################################################################################################################
//################################################################################################################################################
//   THE FOLLOWING CODE IS FOR THE REACH TOOL AUTOSUGGEST AND TOOLTIPS
//################################################################################################################################################
//################################################################################################################################################

    /**
 * An autosuggest textbox control.
 * @class
 * @scope public
 */
function AutoSuggestControl(oTextbox /*:HTMLInputElement*/, 
                            oProvider /*:SuggestionProvider*/) {
    
    /**
     * The currently selected suggestions.
     * @scope private
     */   
    this.cur /*:int*/ = -1;

    /**
     * The dropdown list layer.
     * @scope private
     */
    this.layer = null;
    
    /**
     * Suggestion provider for the autosuggest feature.
     * @scope private.
     */
    this.provider /*:SuggestionProvider*/ = oProvider;
    
    /**
     * The textbox to capture.
     * @scope private
     */
    this.textbox /*:HTMLInputElement*/ = oTextbox;
    
    //initialize the control
    this.init();
    
}

/**
 * Autosuggests one or more suggestions for what the user has typed.
 * If no suggestions are passed in, then no autosuggest occurs.
 * @scope private
 * @param aSuggestions An array of suggestion strings.
 * @param bTypeAhead If the control should provide a type ahead suggestion.
 */
AutoSuggestControl.prototype.autosuggest = function (aSuggestions /*:Array*/,
                                                     bTypeAhead /*:boolean*/) {
    
    //make sure there's at least one suggestion
    if (aSuggestions.length > 0) {
        if (bTypeAhead) {
           this.typeAhead(aSuggestions[0]);
        }
        
        this.showSuggestions(aSuggestions);
    } else {
        this.hideSuggestions();
    }
};

/**
 * Creates the dropdown layer to display multiple suggestions.
 * @scope private
 */
AutoSuggestControl.prototype.createDropDown = function () {

    var oThis = this;

    //create the layer and assign styles
    this.layer = document.createElement("div");
    this.layer.className = "suggestions";
    this.layer.style.visibility = "hidden";
    this.layer.style.width = this.textbox.offsetWidth;
    
    //when the user clicks on the a suggestion, get the text (innerHTML)
    //and place it into a textbox
    this.layer.onmousedown = 
    this.layer.onmouseup = 
    this.layer.onmouseover = function (oEvent) {
        oEvent = oEvent || window.event;
        oTarget = oEvent.target || oEvent.srcElement;

        if (oEvent.type == "mousedown") {
		
            oThis.textbox.value = oTarget.firstChild.nodeValue; 
            oThis.hideSuggestions();
            submitForm();   
        } else if (oEvent.type == "mouseover") {
            oThis.highlightSuggestion(oTarget);
        } else {
           oThis.textbox.focus();
        }
    };
    
    
    document.body.appendChild(this.layer);
};


/**
 * Gets the left coordinate of the textbox.
 * @scope private
 * @return The left coordinate of the textbox in pixels.
 */
AutoSuggestControl.prototype.getLeft = function () /*:int*/ {

    var oNode = this.textbox;
    var iLeft = 0;
    
    while(oNode.offsetParent != null && oNode.tagName != "BODY") {
        iLeft += oNode.offsetLeft;
        oNode = oNode.offsetParent;
    }
   	
    return iLeft;
};

/**
 * Gets the top coordinate of the textbox.
 * @scope private
 * @return The top coordinate of the textbox in pixels.
 */
AutoSuggestControl.prototype.getTop = function () /*:int*/ {

    var oNode = this.textbox;
    var iTop = 0;
    
    while(oNode.offsetParent != null && oNode.tagName != "BODY") {
        iTop += oNode.offsetTop;
        oNode = oNode.offsetParent;
    }
    
    return iTop;
};

/**
 * Handles three keydown events.
 * @scope private
 * @param oEvent The event object for the keydown event.
 */
AutoSuggestControl.prototype.handleKeyDown = function (oEvent /*:Event*/) {

    switch(oEvent.keyCode) {
        case 38: //up arrow
            this.previousSuggestion();
            break;
        case 40: //down arrow 
            this.nextSuggestion();
            break;
        case 13: //enter
            if(this.cur == -1 && this.layer.childNodes.length > 0)
            {
                this.textbox.value = this.layer.childNodes[0].firstChild.nodeValue;          
            }
            submitForm();
            break;
    }

};

/**
 * Handles keyup events.
 * @scope private
 * @param oEvent The event object for the keyup event.
 */
AutoSuggestControl.prototype.handleKeyUp = function (oEvent /*:Event*/) {

    var iKeyCode = oEvent.keyCode;

    //for backspace (8) and delete (46), shows suggestions without typeahead
    if (iKeyCode == 8 || iKeyCode == 46) {
        this.provider.requestSuggestions(this, false);
        this.cur = -1;
    //make sure not to interfere with non-character keys
    } else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode < 46) || (iKeyCode >= 112 && iKeyCode <= 123)) {
        //ignore
    } else {
        //request suggestions from the suggestion provider with typeahead
        this.provider.requestSuggestions(this, false);
        this.cur = -1;
    }
};

/**
 * Hides the suggestion dropdown.
 * @scope private
 */
AutoSuggestControl.prototype.hideSuggestions = function () {
    this.layer.style.visibility = "hidden";
};

/**
 * Highlights the given node in the suggestions dropdown.
 * @scope private
 * @param oSuggestionNode The node representing a suggestion in the dropdown.
 */
AutoSuggestControl.prototype.highlightSuggestion = function (oSuggestionNode) {
    
    for (var i=0; i < this.layer.childNodes.length; i++) {
        var oNode = this.layer.childNodes[i];
        if (oNode == oSuggestionNode) {
            oNode.className = "current"
        } else if (oNode.className == "current") {
            oNode.className = "";
        }
    }
};

/**
 * Initializes the textbox with event handlers for
 * auto suggest functionality.
 * @scope private
 */
AutoSuggestControl.prototype.init = function () {

    //save a reference to this object
    var oThis = this;
    
    //assign the onkeyup event handler
    this.textbox.onkeyup = function (oEvent) {
    
        //check for the proper location of the event object
        if (!oEvent) {
            oEvent = window.event;
        }    
        
        //call the handleKeyUp() method with the event object
        oThis.handleKeyUp(oEvent);
    };
    
    //assign onkeydown event handler
    this.textbox.onkeydown = function (oEvent) {
    
        //check for the proper location of the event object
        if (!oEvent) {
            oEvent = window.event;
        }    
        
        //call the handleKeyDown() method with the event object
        oThis.handleKeyDown(oEvent);
    };
    
    //assign onblur event handler (hides suggestions)    
    this.textbox.onblur = function () {
        oThis.hideSuggestions();
    };
    
    //create the suggestions dropdown
    this.createDropDown();
};

/**
 * Highlights the next suggestion in the dropdown and
 * places the suggestion into the textbox.
 * @scope private
 */
AutoSuggestControl.prototype.nextSuggestion = function () {
    var cSuggestionNodes = this.layer.childNodes;

    if (cSuggestionNodes.length > 0 && this.cur < cSuggestionNodes.length-1) {
        var oNode = cSuggestionNodes[++this.cur];
        this.highlightSuggestion(oNode);
        this.textbox.value = oNode.firstChild.nodeValue; 
    }
};

/**
 * Highlights the previous suggestion in the dropdown and
 * places the suggestion into the textbox.
 * @scope private
 */
AutoSuggestControl.prototype.previousSuggestion = function () {
    var cSuggestionNodes = this.layer.childNodes;

    if (cSuggestionNodes.length > 0 && this.cur > 0) {
        var oNode = cSuggestionNodes[--this.cur];
        this.highlightSuggestion(oNode);
        this.textbox.value = oNode.firstChild.nodeValue;   
    }
};

/**
 * Selects a range of text in the textbox.
 * @scope public
 * @param iStart The start index (base 0) of the selection.
 * @param iLength The number of characters to select.
 */
AutoSuggestControl.prototype.selectRange = function (iStart /*:int*/, iLength /*:int*/) {

    //use text ranges for Internet Explorer
    if (this.textbox.createTextRange) {
        var oRange = this.textbox.createTextRange(); 
        oRange.moveStart("character", iStart); 
        oRange.moveEnd("character", iLength - this.textbox.value.length);      
        oRange.select();
        
    //use setSelectionRange() for Mozilla
    } else if (this.textbox.setSelectionRange) {
        this.textbox.setSelectionRange(iStart, iLength);
    }     

    //set focus back to the textbox
    this.textbox.focus();      
}; 

/**
 * Builds the suggestion layer contents, moves it into position,
 * and displays the layer.
 * @scope private
 * @param aSuggestions An array of suggestions for the control.
 */
AutoSuggestControl.prototype.showSuggestions = function (aSuggestions /*:Array*/) {
    
    var oDiv = null;
    this.layer.innerHTML = "";  //clear contents of the layer
    
    for (var i=0; i < aSuggestions.length; i++) {
        oDiv = document.createElement("div");
        oDiv.appendChild(document.createTextNode(aSuggestions[i]));
        this.layer.appendChild(oDiv);
    }
    
    this.layer.style.left = this.getLeft() + "px";
    this.layer.style.top = (this.getTop()+this.textbox.offsetHeight) + "px";
    this.layer.style.visibility = "visible";
	this.layer.style.width = this.textbox.offsetWidth;

};

/**
 * Inserts a suggestion into the textbox, highlighting the 
 * suggested part of the text.
 * @scope private
 * @param sSuggestion The suggestion for the textbox.
 */
AutoSuggestControl.prototype.typeAhead = function (sSuggestion /*:String*/) {

    //check for support of typeahead functionality
    if (this.textbox.createTextRange || this.textbox.setSelectionRange){
        var iLen = this.textbox.value.length; 
        this.textbox.value = sSuggestion; 
        this.selectRange(iLen, sSuggestion.length);
    }
};

function SubstanceSuggestions() {

}

/**
 * Request suggestions for the given autosuggest control. 
 * @scope protected
 * @param oAutoSuggestControl The autosuggest control to provide suggestions for.
 */
SubstanceSuggestions.prototype.requestSuggestions = function (oAutoSuggestControl /*:AutoSuggestControl*/,
                                                          bTypeAhead /*:boolean*/) {
    var aSuggestions = [];
    var sTextboxValue = oAutoSuggestControl.textbox.value;
    
    if (sTextboxValue.length > 0){
    
        //search for matching states
        var res = 1;
        for (var i=0; i < this.states.length; i++) { 
            if (this.states[i].toLowerCase().indexOf(sTextboxValue.toLowerCase()) >= 0) {
                aSuggestions.push(this.states[i]);
                res ++;
                if(res == 10){
                    //aSuggestions.push('...');
                    break;
                }
            } 
        }
    }

    //provide suggestions to the control
    oAutoSuggestControl.autosuggest(aSuggestions, bTypeAhead);
};

						  

var cX = 0; var cY = 0; var rX = 0; var rY = 0;

function UpdateCursorPosition(e){ cX = e.pageX; cY = e.pageY;}

function UpdateCursorPositionDocAll(e){ cX = event.clientX; cY = event.clientY;}

if(document.all) { document.onmousemove = UpdateCursorPositionDocAll; }

else { document.onmousemove = UpdateCursorPosition; }

function AssignPosition(d) {

    if(self.pageYOffset) {
        rX = self.pageXOffset;
        rY = self.pageYOffset;
    }

    else if(document.documentElement && document.documentElement.scrollTop) {
        rX = document.documentElement.scrollLeft;
        rY = document.documentElement.scrollTop;
    }

    else if(document.body) {
        rX = document.body.scrollLeft;
        rY = document.body.scrollTop;
    }

    if(document.all) 
    {
        cX += rX;
        cY += rY;
    }
    
	var oNode = document.getElementById('primary-content');
    var iLeft = 0;
    
    while(oNode.offsetParent != null && oNode.tagName != "BODY") {
        iLeft += oNode.offsetLeft;
        oNode = oNode.offsetParent;        
    }

 

    var oNode = document.getElementById('primary-content');
    var iTop = 0;
    
    while(oNode.offsetParent != null && oNode.tagName != "BODY") {
        iTop += oNode.offsetTop;
        oNode = oNode.offsetParent;
    }
    
  
     
    d.style.left = (cX-75 - iLeft) + "px";
    d.style.top = (cY+10- iTop) + "px";
}

function HideContent(d) {
    if(d.length < 1) { return; }
    document.getElementById(d).style.display = "none";
}

function ShowContent(d) {
    if(d.length < 1) { return; }
    var dd = document.getElementById(d);
    AssignPosition(dd);
    dd.style.display = "block";
}

function ReverseContentDisplay(d) {

    if(d.length < 1) { return; }
    var dd = document.getElementById(d);
    AssignPosition(dd);
    if(dd.style.display == "none") { dd.style.display = "block"; }
    else { dd.style.display = "none"; }
}

//################################################################################################################################################
//################################################################################################################################################
//################################################################################################################################################
