// cemex Custom JavaScript


// Start Document Ready Calls
$(document).ready(function() {

    /********************************************/
    //		Font Replacement
    /********************************************/
    //Cufon.replace('.cufon', { fontFamily: 'Helvetica Neue' });
    //Cufon.replace('h1', { fontFamily: 'Helvetica Neue' });
    //Cufon.replace('#hub h2', { fontFamily: 'Helvetica Neue' });       
    /********************************************/
    //		Mega Menu Dropdown
    /********************************************/
    if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
        jQuery(".megamenu").megamenu({ 'activate_action': 'click' })
    }
    else {
        jQuery(".megamenu").megamenu();
    }


    /********************************************/
    //		Home Page Rotating Banners
    /********************************************/               
    if($('#navPosition').length > 0  && $('#navPosition').children('.bannerInner').length >= 2 ){       
        $('#navPosition').before('<div id="pagernav">').cycle({
            fx: 'fade',
            speed: 1000,
            timeout: 8000,
            pager: '#pagernav'
        });
    }  
   
    $('#bannerHome').click(function() {   
          //  $('#navPosition').cycle('pause');
        });
    /********************************************/
	//		Video Control Rotating Images
	/********************************************/
    if($('#navPosition').length > 0  && $('#navPosition').children('.videoBlock').length >= 2){       
        $('#navPosition').before('<div id="pagernav">').cycle({
            fx: 'fade',
            speed: 1000,
            timeout: 8000,
            pager: '#pagernav'
        });

        $('.videoBlock').click(function() {
            $('#navPosition').cycle('pause');
        });
        $('.videoModule').click(function() {
            $('#navVideos').cycle('pause');
        });        
    }
            
    /********************************************/
    //		SubPages Rotating Banners
    /********************************************/
    if($('#numberPosition').length > 0 && $('#numberPosition').children().length >= 2){
        $('#numberPosition').before('<div id="numbers">').cycle({
            fx: 'fade',
            speed: 1000,
            timeout: 8000,
            pager: '#numbers'
        });
    }
    

    /**********************************/
    //		Equal Heights Calls
    /**********************************/
    equalHeight($(".equal"));
    equalHeight($(".equalBox"));
    equalHeight($(".equalColumn"));

    /********************************************/
    //		Home Page Fixed Accordion
    /********************************************/
    $(".accordion").tabs(".pane", { tabs: 'h2', effect: 'slide' });
    /********************************************/
    // Accordion Full Width Center Column
    // ilinium
    /********************************************/
    $(".accordionCenter").tabs(".paneCenter", { tabs: 'h3', effect: 'slide', initialIndex: null });
    /********************************************/
    // Accordion Nested Center Column
    // ilinium
    /********************************************/
    $(".accordionInternal").tabs(".paneInternal", { tabs: 'h2', effect: 'slide', initialIndex: null });

    /********************************************/
    //		Content Page Accordion
    /********************************************/
    $('.drawer .drawer-content:not(:first)').hide(); // hide all content drawers extept for the first one
    $('H2.drawer-handle').click(function() {
        // show/hide drawer content
        $('.drawer-content:visible').slideUp().prev().removeClass('open');
        $(this).addClass('open').next().slideDown();
    });

    /********************************************/
    //		Tabs - Sitewide
    /********************************************/
    $("ul.tabs").tabs("> .pane");
    $("ul.tabsSimple").tabs("> .paneSimple");

    /********************************************/
    //		Home Page MAP - Show/Hide Hover
    /********************************************/
    $(".map-box a").click(function(e) {
        $("#areas div").hide();
        $(this.hash).show();
        e.preventDefault();
    });
    $("#areas div:not(#NorthAmerica)").hide();

    /********************************************/
    //		Home Page Carousel
    /********************************************/
    //move he last list item before the first item. The purpose of this is if the user clicks to slide left he will be able to see the last item.
    $('#carousel_ul li:first').before($('#carousel_ul li:last'));

    //when user clicks the image for sliding right        
    $('#right_scroll img').click(function() {

        //get the width of the items ( i like making the jquery part dynamic, so if you change the width in the css you won't have o change it here too ) '
        var item_width = $('#carousel_ul li').outerWidth() + 10;

        //calculae the new left indent of the unordered list
        var left_indent = parseInt($('#carousel_ul').css('left')) - item_width;

        //make the sliding effect using jquery's anumate function '
        $('#carousel_ul:not(:animated)').animate({ 'left': left_indent }, 500, function() {

            //get the first list item and put it after the last list item (that's how the infinite effects is made) '
            $('#carousel_ul li:last').after($('#carousel_ul li:first'));

            //and get the left indent to the default -307px
            $('#carousel_ul').css({ 'left': '-307px' });
        });
    });

    //when user clicks the image for sliding left
    $('#left_scroll img').click(function() {

        var item_width = $('#carousel_ul li').outerWidth() + 10;

        /* same as for sliding right except that it's current left indent + the item width (for the sliding right it's - item_width) */
        var left_indent = parseInt($('#carousel_ul').css('left')) + item_width;

        $('#carousel_ul:not(:animated)').animate({ 'left': left_indent }, 500, function() {

            /* when sliding to left we are moving the last item before the first list item */
            $('#carousel_ul li:first').before($('#carousel_ul li:last'));

            /* and again, when we make that change we are setting the left indent of our unordered list to the default -307px */
            $('#carousel_ul').css({ 'left': '-307px' });
        });


    });

    /**********************************/
    //		Colorbox Lightbox
    /**********************************/
    //$(".youtubeplayer").colorbox({iframe:true, innerWidth:"560", innerHeight:"354"});
    $(".youtubeplayer").colorbox({ width: "650", inline: true,
                                   onComplete: function(){                                          
                                        //This is for Chrome                                                                                                                                                                                                                                                                                                                                                                                           
                                        $("#colorbox").width(660);                                        
                                        $("#cboxWrapper").width(660);   
                                        $(".cboxIE").css("width","660");                                        
                                   }
    });
    $(".wallpaperContainer").colorbox({ width: "900", height: "950", inline: true });
    
    /**************************************************************/
    /*                      City of the Future                    */
    /**************************************************************/    
    if(appleDeviceCheck()){       
        $('#flashStandard').children().hide();
        $('#flashStandard').append("<p style='font-size:11px;'>To view this application requires the correct version of flash player. <a href='http://get.adobe.com/flashplayer/' target='_blank'>Download correct version</a> or you can browse the accessible text based version below.</p>");
    }
});
// End Document Ready Calls

/////////////////////////////////////////////
//Video ToolTip
/////////////////////////////////////////////

$(function(){
	if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
		$(".videoTip").simpletooltip({ click: true, hideDelay: 0.5 });
	}
	else{
		$(".videoTip").simpletooltip();
	}
});

/////////////////////////////////////////////
//jQuery Accordion
/////////////////////////////////////////////

$(function() {
	$("#accordion").tabs("#accordion div.pane", {tabs: 'h2', effect: 'slide', initialIndex: null});
});

/////////////////////////////////////////////

//Equal Heights with JavaScript

/////////////////////////////////////////////

function equalHeight(group) {
    tallest = 0;
    group.each(function() {
        thisHeight = $(this).height();
        if(thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
}

/////////////////////////////////////////////

//Mega Menu

/////////////////////////////////////////////
	
/*
  jQuery MegaMenu Plugin
  Author: GeekTantra
  Author URI: http://www.geektantra.com
*/
var isIE6 = navigator.userAgent.toLowerCase().indexOf('msie 6') != -1;

jQuery.fn.megamenu = function(options) {
  options = jQuery.extend({
	  activate_action: "mouseenter",
	  deactivate_action: "mouseleave",
	  show_method: "slideDown",
	  hide_method: "slideUp",
	  justify: "left",
	  enable_js_shadow: true,
	  //shadow_size: 0,
	  mm_timeout: 250
  }, options);
  var $megamenu_object = this;
  if( options.activate_action == "click" ) options.mm_timeout = 0;
  $megamenu_object.children("li").each(function(){
    jQuery(this).addClass("mm-item");
    jQuery(".mm-item").css({ 'float': options.justify });
    
    jQuery(this).find("div:first").addClass("mm-item-content");
    jQuery(this).find("a:first").addClass("mm-item-link");
    var $mm_item_content = jQuery(this).find(".mm-item-content");
    var $mm_item_link = jQuery(this).find(".mm-item-link");
    $mm_item_content.hide();
    
    jQuery(document).bind("click", function(){
      jQuery(".mm-item-content").hide();
      jQuery(".mm-item-link").removeClass("mm-item-link-hover");
    });
    jQuery(this).bind("click", function(e){
      e.stopPropagation();
    });

	//iPad Fix
	jQuery(this).find("a.mm-item-link").bind("click", function(e){
		if (jQuery(this).parent().find("div.mm-item-content").is(":visible"))
		{
			//Follow the link
		}
		else
		{
			e.preventDefault();
		}
    });
	
	//iPad "X" button to close menu
	jQuery(this).find("a.xclose").bind("click", function(e){
      jQuery(".mm-item-content").hide();
      jQuery(".mm-item-link").removeClass("mm-item-link-hover");
	  e.stopPropagation();
	  return true;
	  
	  //mm_item_content_obj.hide();
      //mm_item_link_obj.removeClass("mm-item-link-hover");
    });

    $mm_item_content.wrapInner('<div class="mm-content-base"></div>');
    if(options.enable_js_shadow == true) {
      $mm_item_content.append('<div class="mm-js-shadow">&nbsp;</div>');
    }
    var $mm_timer = 0;
    // Activation Method Starts
    jQuery(this).bind(options.activate_action, function(e){
      e.stopPropagation();
      var mm_item_link_obj = jQuery(this).find("a.mm-item-link");
      var mm_item_content_obj = jQuery(this).find("div.mm-item-content");
      clearTimeout($mm_timer);
      $mm_timer = setTimeout(function(){ //Emulate HoverIntent
        mm_item_link_obj.addClass("mm-item-link-hover");
        mm_item_content_obj.css({
          'top': ($mm_item_link.offset().top + $mm_item_link.outerHeight()) - 1 +"px",
          'left': ($mm_item_link.offset().left) - 5 + 'px'
        })
        
        if(options.justify == "left"){
          var mm_object_right_end = $megamenu_object.offset().left + $megamenu_object.outerWidth();
                                    // Coordinates of the right end of the megamenu object
          var mm_content_right_end = $mm_item_link.offset().left + $mm_item_content.outerWidth() - 2 ;
                                    // Coordinates of the right end of the megamenu content
          if( mm_content_right_end >= mm_object_right_end ) { // Menu content exceeding the outer box
            mm_item_content_obj.css({
              'left': ($mm_item_link.offset().left - (mm_content_right_end - mm_object_right_end)) - 1 + 'px'
            }); // Limit megamenu inside the outer box
          }
        } else if( options.justify == "right" ) {
          var mm_object_left_end = $megamenu_object.offset().left;
                                    // Coordinates of the left end of the megamenu object
          var mm_content_left_end = $mm_item_link.offset().left - mm_item_content_obj.outerWidth() + 
                                    $mm_item_link.outerWidth() + 5;
                                    // Coordinates of the left end of the megamenu content
          if( mm_content_left_end <= mm_object_left_end ) { // Menu content exceeding the outer box
            mm_item_content_obj.css({
              'left': mm_object_left_end + 2 + 'px'
            }); // Limit megamenu inside the outer box
          } else {
            mm_item_content_obj.css({
              'left': mm_content_left_end + 'px'
            }); // Limit megamenu inside the outer box
          }
        }
        if(options.enable_js_shadow == true) {
          mm_item_content_obj.find(".mm-js-shadow").height( mm_item_content_obj.height() );
          mm_item_content_obj.find(".mm-js-shadow").width( mm_item_content_obj.width() );
          /*mm_item_content_obj.find(".mm-js-shadow").css({
            'top': (options.shadow_size) + (isIE6 ? 2 : 0) + "px",
            'left': (options.shadow_size) + (isIE6 ? 2 : 0) + "px"
            //'opacity': 0.2
          });*/
        }
        switch(options.show_method) {
          case "simple":
                mm_item_content_obj.show();
                break;
          case "slideDown":
                mm_item_content_obj.height("auto");
                mm_item_content_obj.slideDown('fast');
                break;
          case "fadeIn":
                mm_item_content_obj.fadeTo('fast', 1);
                break;
          default:
                mm_item_content_obj.each( options.show_method );
                break;
        }
      }, options.mm_timeout);
    });
    // Activation Method Ends
    // Deactivation Method Starts
    jQuery(this).bind(options.deactivate_action, function(e){
      e.stopPropagation();
      clearTimeout($mm_timer);
      var mm_item_link_obj = jQuery(this).find("a.mm-item-link");
      var mm_item_content_obj = jQuery(this).find("div.mm-item-content");
//      mm_item_content_obj.stop();
      switch(options.hide_method) {
        case "simple":
              mm_item_content_obj.hide();
              mm_item_link_obj.removeClass("mm-item-link-hover");
              break;
        case "slideUp":
              mm_item_content_obj.slideUp( 'fast',  function() {
                mm_item_link_obj.removeClass("mm-item-link-hover");
              });
              break;
        case "fadeOut":
              mm_item_content_obj.fadeOut( 'fast', function() {
                mm_item_link_obj.removeClass("mm-item-link-hover");
              });
              break;
        default:
              mm_item_content_obj.each( options.hide_method );
              mm_item_link_obj.removeClass("mm-item-link-hover");
              break;
      }
    });
//    Deactivation Method Ends
  });
  this.find("li:last").after('<li class="clear-fix"></li>');
  this.show();
};


/***********************************************/
//Accordion (Multiple Sliders)
/***********************************************/
var ddaccordion={
	
	contentclassname:{}, //object to store corresponding contentclass name based on headerclass

	expandone:function(headerclass, selected){ //PUBLIC function to expand a particular header
		this.toggleone(headerclass, selected, "expand")
	},

	collapseone:function(headerclass, selected){ //PUBLIC function to collapse a particular header
		this.toggleone(headerclass, selected, "collapse")
	},

	expandall:function(headerclass){ //PUBLIC function to expand all headers based on their shared CSS classname
		var $=jQuery
		var $headers=$('.'+headerclass)
		$('.'+this.contentclassname[headerclass]+':hidden').each(function(){
			$headers.eq(parseInt($(this).attr('contentindex'))).trigger("evt_accordion")
		})
	},

	collapseall:function(headerclass){ //PUBLIC function to collapse all headers based on their shared CSS classname
		var $=jQuery
		var $headers=$('.'+headerclass)
		$('.'+this.contentclassname[headerclass]+':visible').each(function(){
			$headers.eq(parseInt($(this).attr('contentindex'))).trigger("evt_accordion")
		})
	},

	toggleone:function(headerclass, selected, optstate){ //PUBLIC function to expand/ collapse a particular header
		var $=jQuery
		var $targetHeader=$('.'+headerclass).eq(selected)
		var $subcontent=$('.'+this.contentclassname[headerclass]).eq(selected)
		if (typeof optstate=="undefined" || optstate=="expand" && $subcontent.is(":hidden") || optstate=="collapse" && $subcontent.is(":visible"))
			$targetHeader.trigger("evt_accordion")
	},

	expandit:function($targetHeader, $targetContent, config, useractivated, directclick){
		this.transformHeader($targetHeader, config, "expand")
		$targetContent.slideDown(config.animatespeed, function(){
			config.onopenclose($targetHeader.get(0), parseInt($targetHeader.attr('headerindex')), $targetContent.css('display'), useractivated)
			if (config.postreveal=="gotourl" && directclick){ //if revealtype is "Go to Header URL upon click", and this is a direct click on the header
				var targetLink=($targetHeader.is("a"))? $targetHeader.get(0) : $targetHeader.find('a:eq(0)').get(0)
				if (targetLink) //if this header is a link
					setTimeout(function(){location=targetLink.href}, 200) //ignore link target, as window.open(targetLink, targetLink.target) doesn't work in FF if popup blocker enabled
			}
		})
	},

	collapseit:function($targetHeader, $targetContent, config, isuseractivated){
		this.transformHeader($targetHeader, config, "collapse")
		$targetContent.slideUp(config.animatespeed, function(){config.onopenclose($targetHeader.get(0), parseInt($targetHeader.attr('headerindex')), $targetContent.css('display'), isuseractivated)})
	},

	transformHeader:function($targetHeader, config, state){
		$targetHeader.addClass((state=="expand")? config.cssclass.expand : config.cssclass.collapse) //alternate btw "expand" and "collapse" CSS classes
		.removeClass((state=="expand")? config.cssclass.collapse : config.cssclass.expand)
		if (config.htmlsetting.location=='src'){ //Change header image (assuming header is an image)?
			$targetHeader=($targetHeader.is("img"))? $targetHeader : $targetHeader.find('img').eq(0) //Set target to either header itself, or first image within header
			$targetHeader.attr('src', (state=="expand")? config.htmlsetting.expand : config.htmlsetting.collapse) //change header image
		}
		else if (config.htmlsetting.location=="prefix") //if change "prefix" HTML, locate dynamically added ".accordprefix" span tag and change it
			$targetHeader.find('.accordprefix').html((state=="expand")? config.htmlsetting.expand : config.htmlsetting.collapse)
		else if (config.htmlsetting.location=="suffix")
			$targetHeader.find('.accordsuffix').html((state=="expand")? config.htmlsetting.expand : config.htmlsetting.collapse)
	},

	urlparamselect:function(headerclass){
		var result=window.location.search.match(new RegExp(headerclass+"=((\\d+)(,(\\d+))*)", "i")) //check for "?headerclass=2,3,4" in URL
		if (result!=null)
			result=RegExp.$1.split(',')
		return result //returns null, [index], or [index1,index2,etc], where index are the desired selected header indices
	},

	getCookie:function(Name){ 
		var re=new RegExp(Name+"=[^;]+", "i") //construct RE to search for target name/value pair
		if (document.cookie.match(re)) //if cookie found
			return document.cookie.match(re)[0].split("=")[1] //return its value
		return null
	},

	setCookie:function(name, value){
		document.cookie = name + "=" + value + "; path=/"
	},

	init:function(config){
	document.write('<style type="text/css">\n')
	document.write('.'+config.contentclass+'{display: none}\n') //generate CSS to hide contents
	document.write('<\/style>')
	jQuery(document).ready(function($){
		ddaccordion.urlparamselect(config.headerclass)
		var persistedheaders=ddaccordion.getCookie(config.headerclass)
		ddaccordion.contentclassname[config.headerclass]=config.contentclass //remember contentclass name based on headerclass
		config.cssclass={collapse: config.toggleclass[0], expand: config.toggleclass[1]} //store expand and contract CSS classes as object properties
		config.revealtype=config.revealtype || "click"
		config.revealtype=config.revealtype.replace(/mouseover/i, "mouseenter")
		if (config.revealtype=="clickgo"){
			config.postreveal="gotourl" //remember added action
			config.revealtype="click" //overwrite revealtype to "click" keyword
		}
		if (typeof config.togglehtml=="undefined")
			config.htmlsetting={location: "none"}
		else
			config.htmlsetting={location: config.togglehtml[0], collapse: config.togglehtml[1], expand: config.togglehtml[2]} //store HTML settings as object properties
		config.oninit=(typeof config.oninit=="undefined")? function(){} : config.oninit //attach custom "oninit" event handler
		config.onopenclose=(typeof config.onopenclose=="undefined")? function(){} : config.onopenclose //attach custom "onopenclose" event handler
		var lastexpanded={} //object to hold reference to last expanded header and content (jquery objects)
		var expandedindices=ddaccordion.urlparamselect(config.headerclass) || ((config.persiststate && persistedheaders!=null)? persistedheaders : config.defaultexpanded)
		if (typeof expandedindices=='string') //test for string value (exception is config.defaultexpanded, which is an array)
			expandedindices=expandedindices.replace(/c/ig, '').split(',') //transform string value to an array (ie: "c1,c2,c3" becomes [1,2,3]
		var $subcontents=$('.'+config["contentclass"])
		if (expandedindices.length==1 && expandedindices[0]=="-1") //check for expandedindices value of [-1], indicating persistence is on and no content expanded
			expandedindices=[]
		if (config["collapseprev"] && expandedindices.length>1) //only allow one content open?
			expandedindices=[expandedindices.pop()] //return last array element as an array (for sake of jQuery.inArray())
		if (config["onemustopen"] && expandedindices.length==0) //if at least one content should be open at all times and none are, open 1st header
			expandedindices=[0]
		$('.'+config["headerclass"]).each(function(index){ //loop through all headers
			if (/(prefix)|(suffix)/i.test(config.htmlsetting.location) && $(this).html()!=""){ //add a SPAN element to header depending on user setting and if header is a container tag
				$('<span class="accordprefix"></span>').prependTo(this)
				$('<span class="accordsuffix"></span>').appendTo(this)
			}
			$(this).attr('headerindex', index+'h') //store position of this header relative to its peers
			$subcontents.eq(index).attr('contentindex', index+'c') //store position of this content relative to its peers
			var $subcontent=$subcontents.eq(index)
			var needle=(typeof expandedindices[0]=="number")? index : index+'' //check for data type within expandedindices array- index should match that type
			if (jQuery.inArray(needle, expandedindices)!=-1){ //check for headers that should be expanded automatically (convert index to string first)
				if (config.animatedefault==false)
					$subcontent.show()
				ddaccordion.expandit($(this), $subcontent, config, false) //Last param sets 'isuseractivated' parameter
				lastexpanded={$header:$(this), $content:$subcontent}
			}  //end check
			else{
				$subcontent.hide()
				config.onopenclose($(this).get(0), parseInt($(this).attr('headerindex')), $subcontent.css('display'), false) //Last Boolean value sets 'isuseractivated' parameter
				ddaccordion.transformHeader($(this), config, "collapse")
			}
		})
		$('.'+config["headerclass"]).bind("evt_accordion", function(e, isdirectclick){ //assign custom event handler that expands/ contacts a header
				var $subcontent=$subcontents.eq(parseInt($(this).attr('headerindex'))) //get subcontent that should be expanded/collapsed
				if ($subcontent.css('display')=="none"){
					ddaccordion.expandit($(this), $subcontent, config, true, isdirectclick) //2nd last param sets 'isuseractivated' parameter
					if (config["collapseprev"] && lastexpanded.$header && $(this).get(0)!=lastexpanded.$header.get(0)){ //collapse previous content?
						ddaccordion.collapseit(lastexpanded.$header, lastexpanded.$content, config, true) //Last Boolean value sets 'isuseractivated' parameter
					}
					lastexpanded={$header:$(this), $content:$subcontent}
				}
				else if (!config["onemustopen"] || config["onemustopen"] && lastexpanded.$header && $(this).get(0)!=lastexpanded.$header.get(0)){
					ddaccordion.collapseit($(this), $subcontent, config, true) //Last Boolean value sets 'isuseractivated' parameter
				}
 		})
		$('.'+config["headerclass"]).bind(config.revealtype, function(){
			if (config.revealtype=="mouseenter"){
				clearTimeout(config.revealdelay)
				var headerindex=parseInt($(this).attr("headerindex"))
				config.revealdelay=setTimeout(function(){ddaccordion.expandone(config["headerclass"], headerindex)}, config.mouseoverdelay || 0)
			}
			else{
				$(this).trigger("evt_accordion", [true])
				return false //cancel default click behavior
			}
		})
		$('.'+config["headerclass"]).bind("mouseleave", function(){
			clearTimeout(config.revealdelay)
		})
		config.oninit($('.'+config["headerclass"]).get(), expandedindices)
		$(window).bind('unload', function(){ //clean up and persist on page unload
			$('.'+config["headerclass"]).unbind()
			var expandedindices=[]
			$('.'+config["contentclass"]+":visible").each(function(index){ //get indices of expanded headers
				expandedindices.push($(this).attr('contentindex'))
			})
			if (config.persiststate==true && $('.'+config["headerclass"]).length>0){ //persist state?
				expandedindices=(expandedindices.length==0)? '-1c' : expandedindices //No contents expanded, indicate that with dummy '-1c' value?
				ddaccordion.setCookie(config.headerclass, expandedindices)
			}
		})
	})
	}
}

/***********************************************/
// Accordion (Expand/Collapse)
/***********************************************/

ddaccordion.init({
	headerclass: "trigger", //Shared CSS class name of headers group
	contentclass: "triggerContent", //Shared CSS class name of contents group
	revealtype: "click", //Reveal content when user clicks or onmouseover the header? Valid value: "click", "clickgo", or "mouseover"
	mouseoverdelay: 200, //if revealtype="mouseover", set delay in milliseconds before header expands onMouseover
	collapseprev: false, //Collapse previous content (so only one open at any time)? true/false 
	defaultexpanded: [], //index of content(s) open by default [index1, index2, etc]. [] denotes no content.
	onemustopen: false, //Specify whether at least one header should be open always (so never all headers closed)
	animatedefault: false, //Should contents open by default be animated into view?
	persiststate: false, //persist state of opened contents within browser session?
	toggleclass: ["closedlanguage", "openlanguage"], //Two CSS classes to be applied to the header when it's collapsed and expanded, respectively ["class1", "class2"]
	//togglehtml: ["prefix", "<img src='http://i13.tinypic.com/80mxwlz.gif' style='width:13px; height:13px' /> ", "<img src='http://i18.tinypic.com/6tpc4td.gif' style='width:13px; height:13px' /> "], //Additional HTML added to the header when it's collapsed and expanded, respectively  ["position", "html1", "html2"] (see docs)
	animatespeed: "fast", //speed of animation: integer in milliseconds (ie: 200), or keywords "fast", "normal", or "slow"
	oninit:function(expandedindices){ //custom code to run when headers have initalized
		//do nothing
	},
	onopenclose:function(header, index, state, isuseractivated){ //custom code to run whenever a header is opened or closed
		//do nothing
	}
})


/////////////////////////////////////////////

//Changing Map images on click

/////////////////////////////////////////////

function changeIt(objName)
{
	//The image object accessed through its id we mentioned in the DIV block which is going to be visible currently
	var obj = document.getElementById(objName);
	
	//An array that hold the IDs of images that we mentioned in their DIV blocks
	var objId = new Array();
	
	//Storing the image IDs into the array starts here
	objId[0] = "image1";
	objId[1] = "image2";
	objId[2] = "image3";
	objId[3] = "image4";
	objId[4] = "image5";
	//Storing the image IDs into the array ends here
	
	//A counter variable going to use for iteration
	var i;
	
	//A variable that can hold all the other object references other than the object which is going to be visible
	var tempObj;
	
	//The following loop does the display of a single image based on its ID. The image whose ID we passed into this function will be the
	//only image that is displayed rest of the images will be hidden based on their IDs and that part has been handled by the else part
	//of the if statement within this loop.
	for(i=0;i<objId.length;i++)
	{
		if(objName == objId[i])
		{
			obj.style.display = "block";
		}
		else
		{
			tempObj = document.getElementById(objId[i]);
			tempObj.style.display = "none";	
		}
	}
	return;	
}


/////////////////////////////////////////////

//Country Dropdown Menu

/////////////////////////////////////////////
var timeout	= 100;
var closetimer	= 0;
var ddmenuitem	= 0;

// open hidden layer
function mopen(id)
{	
	// cancel close timer
	mcancelclosetime();

	// close old layer
	if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';

	// get new layer and show it
	ddmenuitem = document.getElementById(id);
	ddmenuitem.style.visibility = 'visible';

}
// close showed layer
function mclose()
{
	if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';
}

// go close timer
function mclosetime()
{
	closetimer = window.setTimeout(mclose, timeout);
}

// cancel close timer
function mcancelclosetime()
{
	if(closetimer)
	{
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}

// close layer when click-out
document.onclick = mclose;

/***********************************************/

/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){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;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);

//Contact Us Functions
//ILINIUM

/////////////////////////////////////////////

function CheckText(sender, args) {
    var vText = args.Value;

    if (vText != "" && !(isInvalidSpecialChars(vText))) {
        args.IsValid = true;
    } else {
        args.IsValid = false;
    }
}

function CheckCombo(sender, args){

    var vArea = args.Value;

    if (vArea != "") {       
	    args.IsValid = true;                 
    }
    else
    {
        args.IsValid = false;
    }    
}

function isInvalidSpecialChars(psText) {
    return psText.search(/\<|\>|\#/) > -1
}

function imposeMaxLength(Object, MaxLen) {
    return (Object.value.length < MaxLen);
}

function validatePaste(Object, MaxLen) {
    if (Object.value.length + window.clipboardData.getData('Text').length > MaxLen) {
        event.returnValue = false;
    }
}


/////////////////////////////////////////////

//Report Functions
//ILINIUM

/////////////////////////////////////////////

function CheckArea(sender, args){

    var vArea = args.Value;

    if (vArea != "-1") {       
	    args.IsValid = true;                 
    }
    else
    {
        args.IsValid = false;
    }    
}

function CheckText(sender, args){
    var vText = args.Value;
   
    if(vText != "" && !(isInvalidSpecialChars(vText))){
        args.IsValid = true;
    }else
    {
        args.IsValid = false;
    }
}

function IsNumeric(ctrl){
	if(!(IsInteger(ctrl.value))){
		if(isNaN(parseInt(ctrl.value))){
			ctrl.value = "";
		}else{
			ctrl.value = parseInt(ctrl.value);				
		}
	}	
}

function IsInteger(str){	
	if (typeof(str)=='undefined'){
		return false;
	}
	var expr = /^[\+\-]?[0-9]*$/;
	if (!expr.test(str)){
		return false;
	}
	return true;
}

function IsUnSignedInteger(str){	
	if (typeof(str)=='undefined'){
		return false;
	}
	var expr = /^[0-9]*$/;
	if (!expr.test(str)){
		return false;
	}
	return true;
}
function IsUnSignedNumeric(ctrl){
	if(!(IsUnSignedInteger(ctrl.value))){
		if(isNaN(parseInt(ctrl.value))){
			ctrl.value = "";
		}else{
			ctrl.value = parseInt(ctrl.value);				
		}
	}	
}	
	
function validateControl(Object){
    if(trim(Object.value) != ''){
        if(isInvalidSpecialChars(Object.value)){
            alert("Invalid character(s) on the field:" + Object.name);
            Object.focus();
            return false;
        }        
    }
}

function trim(str){
	return str.replace(/^\s*|\s*$/g,"");
}

/////////////////////////////////////////////

//Modal Window
//ILINIUM

/////////////////////////////////////////////

/********************************************/
//		Cases Stories Rotating Banners
/********************************************/

function appleDeviceCheck() {
    var agent = navigator.userAgent.toLowerCase();
    var iphone = (agent.indexOf('iphone') != -1 || agent.indexOf('ipad') != -1 || agent.indexOf('ipod') != -1);
    return iphone
}

$(document).ready(function() {    
    if(($('#navCaseStudy').length > 0) && ($('#navCaseStudy').children('.videoModule').length >= 2)){
        $('#navCaseStudy').before('<div id="pagernav">').cycle({
            fx: 'fade',
            speed: 1000,
            timeout: 8000,
            pager: '#pagernav'
        });    
    }    
    /********************************************/
    //		Video modal
    /********************************************/    
    if($('#navVideos').length > 0 && $('#navVideos').children('.videoModule').length >= 2){        
        $('#navVideos').before('<div id="pagernavVideo">').cycle({
            fx: 'fade',
            speed: 1000,
            timeout: 8000,
            pager: '#pagernavVideo'
        });                
    }

    if (appleDeviceCheck()) {
        $('#videoIphone').show();
        $('#videoStandard').hide();
    }
    $('a[name=modal]').click(function(e) {
        e.preventDefault();
        var id = $(this).attr('href');

        placeModalMask(id);
    });

    /*----- Begin VideoCase control in Landing Pages -----*/
    $('a[name=modalHeader]').click(function(e) {
        var children = $('#hub').children('#modal');
        if (children.length == 0) { $('#modal').appendTo('#hub'); }

        e.preventDefault();
        var id = $(this).attr('href');
        placeModalMask(id);
    });
    /*----- End VideoCase control in Landing Pages -----*/

    $('.window').click(function(e) {
        e.preventDefault();
        stop();
        $('#modalMask, .window').hide();
        $("#ytapiplayer").hide();
    });

    $('#modalMask').click(function() {
        stop();
        $(this).hide();
        $('.window').hide();
        $("#ytapiplayer").hide();
        stop();
    });

    /********************************************/
    //		Wallpaper Modal Window
    /********************************************/
    $('a[name=modalWallpaper]').click(function(e) {
        e.preventDefault();
        var id = $(this).attr('href');
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();
               
        var winW = $(window).width();
        var top = $(window).scrollTop() + 70;        
        $('#modalMaskWallpaper').css({ 'width': maskWidth, 'height': maskHeight, 'top': 0, 'left': 0, 'display': 'block', 'position':'fixed' });
        $('#modalMaskWallpaper').fadeTo("fast", 0.8);

        $(id).css('top', top);
        $(id).css('left', (winW - $(id).width()) / 2);

        $(id).fadeIn(20);
    });

    $('.closeWallpaper').click(function(e) {
        e.preventDefault();
        $('#modalMaskWallpaper, #wallpaper').hide();
    });

    $('#modalMaskWallpaper').click(function() {
        $(this).hide();
        $('#wallpaper').hide();
    });
});
/*---- BEGIN Common Function for Modal Window ----*/
function placeModalMask(id) {
    var maskHeight = $(document).height();
    var maskWidth = $(window).width();    
    var winW = $(window).width();
    var top = $(window).scrollTop()+70;
    
    if (appleDeviceCheck()) {
        $('#videoIphone').show();
        $('#videoStandard').hide();
    } else {
        $('#modalMask').css({ 'width': maskWidth, 'height': maskHeight, 'top': 0, 'left': 0, 'display': 'block' });
        $('#modalMask').fadeTo("fast", 0.8);

        $(id).css('top', top);//winH / 2 - $(id).height() / 2);
        $(id).css('left', (winW - $(id).width()) / 2);

        $(id).fadeIn(20);
        $("#ytapiplayer").show();

        $('#videoStandard').show();
        $('#videoIphone').hide();
    }
}
/*---- END Common Function for Modal Window ----*/

/********************************************/
//		Accordion Select Content
/********************************************/
function SetAccordionContent(){

    var url = location.href.toLowerCase();

    if(url.indexOf("mediacenter") != -1)
    {
        return 0;
    }
    if(url.indexOf("aboutus") != -1)
    {
        return 0;
        //return 1;
    }
    if(url.indexOf("investorcenter") != -1)
    {
        return 0;
        //return 2;
    }    
    if(url.indexOf("productsservices") != -1)
    {
        return 1;
        //return 3;
    }
    if(url.indexOf("sustainabledevelopment") != -1)
    {
        return 4;
    }
    if(url.indexOf("careers") != -1)
    {
        return 0;
        //return 5;
    }        
    return 0;
}

/********************************************/
//		Countries dropdown for content
//      ilinium    
/********************************************/
function showCountries() {
    cancelTimerCountries()
	/*obtiene las coordenadas del span donde se encuentra el link
	  y en base a ellas posiciona el div*/
	var curtop = 0;
	var curleft = 0;
	var obj = document.getElementById("cemexWebsiteLink");
	if (obj.offsetParent) {
		do {
		    curtop += obj.offsetTop;
		    curleft += obj.offsetLeft;
		} while (obj = obj.offsetParent);
	}
	
	var blck = document.getElementById("cemexWebsite");
    blck.style.visibility = 'visible';
	blck.style.top = curtop-180;
	//blck.style.left = curleft-1;
}

function hideCountries() {
	var blck = document.getElementById("cemexWebsite");
    blck.style.visibility = 'hidden';
} 

var countryTimer = 0;

function timerCountries() {
	countryTimer = window.setTimeout(hideCountries, 100);
}

function cancelTimerCountries() {
	if(countryTimer) {
		window.clearTimeout(countryTimer);
		countryTimer = null;
	}
}
