/*
 * jQuery history plugin
 *
 * Copyright (c) 2006 Taku Sano (Mikage Sawatari)
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Modified by Lincoln Cooper to add Safari support and only call the callback once during initialization
 * for msie when no initial hash supplied.
 * API rewrite by Lauris Buk�is-Haberkorns
 * IE8 support added by Jonathan Francis (unpublished)
 */



(function($) {

function History() {
	this._curHash = '';
	this._callback = function(hash){};
}

$.extend(History.prototype, {

	init: function(callback) {
		this._callback = callback;
		this._curHash = location.hash;

		if($.browser.msie && $.browser.version < 8) {
			// To stop the callback firing twice during initilization if no hash present
			if (this._curHash == '') {
				this._curHash = '#';
			}

			// add hidden iframe for IE
			$("body").prepend('<iframe id="jQuery_history" style="display: none;"></iframe>');
			var iframe = $("#jQuery_history")[0].contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = this._curHash;
		}
		else if ($.browser.safari) {
			// etablish back/forward stacks
			this._historyBackStack = [];
			this._historyBackStack.length = history.length;
			this._historyForwardStack = [];
			this._isFirst = true;
			this._dontCheck = false;
		}
		this._callback(this._curHash.replace(/^#/, ''));
		setInterval(this._check, 100);
	},

	add: function(hash) {
		// This makes the looping function do something
		this._historyBackStack.push(hash);

		this._historyForwardStack.length = 0; // clear forwardStack (true click occured)
		this._isFirst = true;
	},

	_check: function() {
		if($.browser.msie && $.browser.version < 8) {
			// On IE, check for location.hash of iframe
			var ihistory = $("#jQuery_history")[0];
			var iframe = ihistory.contentDocument || ihistory.contentWindow.document;
			var current_hash = iframe.location.hash;
			if(current_hash != $.history._curHash) {

				location.hash = current_hash;
				$.history._curHash = current_hash;
				$.history._callback(current_hash.replace(/^#/, ''));

			}
		} else if ($.browser.safari) {
			if (!$.history._dontCheck) {
				var historyDelta = history.length - $.history._historyBackStack.length;

				if (historyDelta) { // back or forward button has been pushed
					$.history._isFirst = false;
					if (historyDelta < 0) { // back button has been pushed
						// move items to forward stack
						for (var i = 0; i < Math.abs(historyDelta); i++) $.history._historyForwardStack.unshift($.history._historyBackStack.pop());
					} else { // forward button has been pushed
						// move items to back stack
						for (var i = 0; i < historyDelta; i++) $.history._historyBackStack.push($.history._historyForwardStack.shift());
					}
					var cachedHash = $.history._historyBackStack[$.history._historyBackStack.length - 1];
					if (cachedHash != undefined) {
						$.history._curHash = location.hash;
						$.history._callback(cachedHash);
					}
				} else if ($.history._historyBackStack[$.history._historyBackStack.length - 1] == undefined && !$.history._isFirst) {
					// back button has been pushed to beginning and URL already pointed to hash (e.g. a bookmark)
					// document.URL doesn't change in Safari
					if (document.URL.indexOf('#') >= 0) {
						$.history._callback(document.URL.split('#')[1]);
					} else {
						$.history._callback('');
					}
					$.history._isFirst = true;
				}
			}
		} else {
			// otherwise, check for location.hash
			var current_hash = location.hash;
			if(current_hash != $.history._curHash) {
				$.history._curHash = current_hash;
				$.history._callback(current_hash.replace(/^#/, ''));
			}
		}
	},

	load: function(hash) {
	  
		var newhash;

		if ($.browser.safari) {
			newhash = hash;
		} else {
			newhash = '#' + hash;
			location.hash = newhash;
		}
		this._curHash = newhash;

		if ($.browser.msie && $.browser.version < 8) {
			var ihistory = $("#jQuery_history")[0]; // TODO: need contentDocument?
			var iframe = ihistory.contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = newhash;
			this._callback(hash);
		}
		else if ($.browser.safari) {
			this._dontCheck = true;
			// Manually keep track of the history values for Safari
			this.add(hash);

			// Wait a while before allowing checking so that Safari has time to update the "history" object
			// correctly (otherwise the check loop would detect a false change in hash).
			var fn = function() {$.history._dontCheck = false;};
			window.setTimeout(fn, 200);
			this._callback(hash);
			// N.B. "location.hash=" must be the last line of code for Safari as execution stops afterwards.
			//      By explicitly using the "location.hash" command (instead of using a variable set to "location.hash") the
			//      URL in the browser and the "history" object are both updated correctly.
			location.hash = newhash;
		}
		else {
		  this._callback(hash);
		}
	}
});

$(document).ready(function() {
	$.history = new History(); // singleton instance
});

})(jQuery);



(function($) {
	$.fn.customFadeIn = function(speed, callback) {
		
		  $(this).fadeIn(speed, function() {
			  if(jQuery.browser.msie)
				  $(this).get(0).style.removeAttribute('filter');
			  if(callback != undefined)
				  callback();
		  });
		
	};
	$.fn.customFadeOut = function(speed, callback) {
	  
  		$(this).fadeOut(speed, function() {
  			if(jQuery.browser.msie)
  				$(this).get(0).style.removeAttribute('filter');
  			if(callback != undefined)
  				callback();
  		});
    
	};
})(jQuery);

globalCarousel = '';
visibleItem = -1;
pageLoad = true;
var AutoScrollTimer = 8;
$(function() {
  $("#carousel").jcarousel({
    initCallback: csCarouselInitCallback,
    itemVisibleOutCallback: {
      onBeforeAnimation: csCarousel_itemBeforeVisibleOutCallback
      },
    itemVisibleInCallback: {
      onAfterAnimation: csCarousel_itemAfterVisibleInCallback
      },
    buttonNextHTML: null,
    buttonPrevHTML: null,
    scroll: 1,
    visible: 1,
    animation: "slow",
    size: 6,
    wrap: "circular",
    auto: AutoScrollTimer
  });

  //re-write the HREFs in the anchor tag.
  $(".jcarousel-control li.control-item-primary > a").each(function() {
    var curr_href = $(this).attr("href");
    $(this).attr("href", "#"+curr_href);
  });
  
  //re-write the HREFs in paged anchors
  $(".jcarousel-control ul.pager li a").each(function() {
    var curr_href = $(this).attr("href");
    $(this).attr("href", "#"+curr_href);
  });

  // Initialize the history controler
  $.history.init(historyCallback);
  init_expandable_menus();
  
});

//function csCarousel_itemAfterVisibleOutCallback(carousel, item, i, state, evt) {
//  carousel.remove(i);
//}

function csCarousel_itemBeforeVisibleOutCallback(carousel, item, i, state, evt) {
  if( 0 < carousel.options.auto ){
    var offset = 1;
  } else {
    if( 1 == i ){ var offset = 1; }
    if( 2 == i ){ var offset = -1; }
  }
  var element = carousel.get(i+offset); //get the next item to determine whether to fade or let the carousel slide
  var elementID = element.find("div").attr("id");
  if( elementID ){
    var id = elementID.split('-');

    var navigationItem = $("#control-item-secondary-nid-"+id[1]);
    if( navigationItem.parent().hasClass("pager") ){ // check whether the next item is in a pager
      $(".jcarousel-clip .node-inner").css({"opacity":0});
      carousel.options.animation = 0;	
      carousel.reload();
    } else {
      $(".jcarousel-clip .node-inner").css({"opacity":1});
    }
  } 
}

/**
 * When the selected item is visible in the carousel, this function is called.
 */
function csCarousel_itemAfterVisibleInCallback(carousel, item, i, state, evt) {

  var element = carousel.get(i);
  var elementInner = element.find("div");
  if( !elementInner.attr("id") ){
    return;    
  }
  var id = elementInner.attr("id").split('-');
  var currentItemNid = id[1];
  var subheaderItemNid = currentItemNid;
  
  // Pager items should show their parents' subheaders. But clicking in the pager also should not hide that subheader.
  var navElement = $('.control-item-nid-'+currentItemNid); // get the navigation item that corresponds to the visible pane
  if( navElement.hasClass("control-item-secondary") ){ 
    var parent = navElement.parents(".control-item-primary"); // for secondary items, get the parent item
    var id = parent.attr("id").split('-');  // get the id of the parent item.
    var subheaderItemNid = id[4];  
  }
  
  // Show the subheader for the current item, hide anything that isn't the current one.
  $(".showcase-subheader-item:not(.showcase-subheader-item-nid-"+subheaderItemNid+")").removeClass("visible").customFadeOut("slow");
  $(".showcase-subheader-item-nid-" + subheaderItemNid).addClass("visible").customFadeIn("slow");  
  
  $(".control-item a.active").removeClass("active");
  $(".control-item-primary-nid-"+currentItemNid+" a:first").addClass("active");
  $(".control-item-secondary-nid-"+currentItemNid+" a:first").addClass("active"); // kludge. We really need a class with the nid that doesn't respect primary / secondary distinction.   
  
  var navigationItem = $("#control-item-secondary-nid-"+currentItemNid);
  if( navigationItem.parent().hasClass("pager") ){
    $(".jcarousel-clip .node-inner").animate({"opacity": 1}, 500);
  } else {
    $(".jcarousel-clip .node-inner").css({"opacity": 1});
  }
  carousel.options.animation = "slow";
  carousel.reload();
}


/**
 * BACKGROUND: no-repeat left top;
 * FILTER: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="http://ldev.c-sgroup.com/files/carousel_images/our_products_acrovyn-wall_s.png",sizingMethod="scale");
 * HEIGHT: 25px
*/
function csCarouselInitCallback(carousel, state) {
  globalCarousel = carousel;

  buildCarouselObject(carousel, state);

  // Now on the navigational links, build the click events to affect the carousel. 
  $(".control-item-primary > a").click(function() {
    var hash = this.href.replace(/^.*#/,'').concat();
    $.history.load(hash);

    return false; //navigationalClick(this, carousel);
  });

  /**
   * This bit of code can be considered the controler for the extra link added to the front page, titled
   * "Our Products" and also when the mouse hovers over the product overlay links.
   *
   * This codes halts the autoscrolling feature and the timer to hide the product overlays.
   */
  //$("#node-1507 .carousel-item-links A,LI#control-item-primary-nid-1507 UL LI.control-item A").mouseover(function() {
  //  window.clearInterval(globalCarousel.timer);
  //  globalCarousel.options.auto = 0;
  //  clearTimeout(initial_product_overlay_fadeout_with_auto_scroll);
  //});

}

function buildCarouselObject(carousel, state) {
  // This will select all primary carousel items and build the carousel object.
  // This is done for the auto scroll feature.
  
  var pagerItems = $(".jcarousel-control ul.pager:eq(0) li.control-item-secondary");
  var parentItem = $(".jcarousel-control ul.pager:eq(0)").parents("li.control-item-primary");
  var items = [];
  //var items = [parentItem];
  pagerItems.each(function(index, pagerItem){
    items.push(pagerItem);
  });
  
  carousel.size(items.length);
  carousel.reload();  
  
  //$(".jcarousel-control ul li.control-item-primary ul.pager:eq(0) li.control-item-secondary").each(function(i){
  $(items).each(function(i){
    var id = $(this).attr("id").split('-');
    var nid = id[4];
    var item = $(".carousel-pane-nid-" + nid).html();
    carousel.add(i + 1, item );
    //console.log('added '+id);
  });

  //carousel.reload();

  //For some reason, IE 6 was not displaying the first item loaded. So here we
  //simply load it again, and that seems to fix it.
  //var id_first = $(".jcarousel-control ul li.control-item-primary").eq(0).attr("id").split('-');
  //carousel.add( 1, $(".carousel-pane-nid-" + id_first[4]).html() );
}

/**
 * Whenever a navigational/control item has been clicked, then this function is called.
 */
firstTime = true;
initial_product_overlay_fadeout_with_auto_scroll = '';
function historyCallback(hash) {
  
  var InitialObjectToDisplay_selector = ".jcarousel-control a[href='#/showcase/our-products']";
  if (hash != '') { // If hash contains a value, then use the hash to slide the carousel and show/hide overlays, etc...
    
    navigationalClick($(".jcarousel-control a[href='#"+hash+"']"), globalCarousel, true, true);
   
  } else {
    if (!firstTime) { // Looks like we're viewing the initial load of the homepage and somebody clicked the back button. So display the right content.
      
      navigationalClick($(InitialObjectToDisplay_selector), globalCarousel, true, true, false);


      //fadeOverlay($(".jcarousel-control a[href='#/showcase/our-products']"), $(".jcarousel-control a[href='#/showcase/our-products']").parent());
      //var theObject = $(".jcarousel-control a:first");
      //navigationalClick(theObject, globalCarousel, false, true);
      //$(".jcarousel-control UL LI UL").customFadeOut('slow');
      //$(".jcarousel-control UL").removeClass("expanded");

    } else { // This code will be exec when the page is initially loaded.
      
      var jQuery_selectorObj = $(InitialObjectToDisplay_selector);
      fadeOverlay(jQuery_selectorObj, $(jQuery_selectorObj).parent(), true);

      //initial_product_overlay_fadeout_with_auto_scroll = setTimeout(function() {
      //    hideOverlay($(".jcarousel-control a[href='#/showcase/featured-project']"))
      //}, AutoScrollTimer*1000);
      
      firstTime = false;

    }
  }
}

function navigationalClick(clickedObj, carousel, overlay, animate, firsttime) {
  var clickedObj_parent = $(clickedObj).parent();
  var id = clickedObj_parent.parent().attr("id").split('-'); // first step of getting the nid
  var nid = id[4];

		if (!firsttime || firsttime == null)
				carousel.options.auto = 0;                                               // Make certain to no longer scroll the content.


  if(clickedObj.parents("ul").hasClass("pager")){   // pager items get a fade transition
    carouselScroll(carousel, clickedObj, false);    // Scroll item into view
    //console.log('pager item clicked');
  } else {
    carouselScroll(carousel, clickedObj, animate);  // Scroll item into view
  }

  $("a.active").removeClass("active");
  $(clickedObj).addClass("active");

  if (overlay) {
    var clickedObj_parent_3 = clickedObj_parent.parent().parent();
    if (clickedObj_parent_3.hasClass("control-item-primary")) {
      fadeOverlay(clickedObj_parent_3.find("A:first"));
    } else {
      fadeOverlay(clickedObj, clickedObj_parent);
    }
  }
  
  if(clickedObj.parents("li").hasClass("control-item-pager-parent")){
    clickedObj.parents("ul").addClass("pager-expanded");
  } else {
    clickedObj.parents("ul").removeClass("pager-expanded");
  }
  
  // Add additional classes to show the pager
  //$("li.control-item-pager-parent > a").click(function(){
  //  $(this).parents("ul").addClass("pager-expanded");
    
  //  return false;
  //});
  
  //$("ul.pager-expanded > li:not(.control-item-pager-parent) > a").click(function(){
  //  $(this).parents("ul").removeClass("pager-expanded");
    
  //  return false;
  //});
  
  
  init_expandable_menus()
  return false;
}

function hideOverlay(clickedObj,animate) {
  if (animate == true || animate == null)
    animate = "slow";
  else
    animate = 0;

  var not_clickedObj_parent = $("li.control-item-primary a").not(clickedObj).parent();
  not_clickedObj_parent.find("ul").customFadeOut(animate, function() {
    not_clickedObj_parent.removeClass("expanded");
    not_clickedObj_parent.parent().removeClass("expanded");
  }); // fade out all other sub menus
}

function fadeOverlay(clickedObj, clickedObj_parent, animate) {
  
  
  if (animate == true || animate == null)
    animate = "slow";
  else
    animate = 0;

  if (clickedObj_parent == '' || clickedObj_parent === undefined)
    clickedObj_parent = $(clickedObj).parent();

  // If this item is a primary item then look for a child ul to expand
  if( clickedObj_parent.hasClass("control-item-primary") ) {                 // we only want to run the code for the primary menu system

    hideOverlay(clickedObj);

    if( 0 < clickedObj_parent.find("ul").size() ) {  // if there content in the UL container, then we have some new content to display.
      clickedObj_parent.find("ul").customFadeIn(animate); // fade in the content.
      clickedObj_parent.addClass("expanded");
      clickedObj_parent.parent().addClass("expanded");
    }
  }
}


/**
 * This function is designed to scroll/slide to the proper slide in the carousel jQuery Plugin.
 *
 * @param <obj> carousel object - this is the ccarousel that we're modifying.
 * @param <obj> Anchor DOM object - this is the anchor that we're accessing
 *
 */

function carouselScroll(carouselObj, anchorObj, ani) {
  unbind_expandable_menus();
  var scrollTo = jQuery.jcarousel.intval($(".jcarousel-control ul.control LI.control-item").index($(anchorObj).parent())); // Get the index value of the LI item that the anchor (that we clicked on) is contained.
 
	// only calculate the carousel slide if we are changing positions.
	if (scrollTo==visibleItem && visibleItem!= -1) {
    return ;
  }

  var id = $(anchorObj).parent().attr("id").split('-'); // first step of getting the nid
  var nid = id[4];

  var first=0;
		var second=0;

	// Which direction are we going? sliding left or sliding right? This controls the placement of the images into the carousel.
	// It's possible to take out this branch (else).
	if (scrollTo < visibleItem) {
		first = 2;
		second = 1;
	} else {
		first = 1;
		second = 2;
	}

	carouselObj.lock();																		// Don't display the changes in the carousel.
	prev_nid = $(".jcarousel-item[jcarouselindex='"+jQuery.jcarousel.intval(carouselObj.first)+"'] .ntype-carousel-item:first").attr('id').split("-")[1];

  carouselObj.add(first, $(".carousel-pane-nid-" + prev_nid).html());		// this will replace the index (first) with the slide.
	carouselObj.add(second, $(".carousel-pane-nid-" + nid).html());   // this will replace the index (second) with the slide.
	visibleItem = scrollTo;															// Update the global varialbe with what is now the current slide.

	carouselObj.size(2);																	// update the size of the carousel.

  // set the timeout to account for fade delay when not sliding
  //if(!ani){
  //  var animationTimeout = 500;
  //} else {
  //  var animationTimeout = 0;
  //}
  //setTimeout(function(){
  //  carouselScroll(carousel, clickedObj, false);// Scroll item into view
  //}, 500);
  //setTimeout(function(){
  //  $(".jcarousel-clip .node-inner").animate({"opacity": 1},500);
  //}, 500);	
	
	carouselObj.reload();																  // reload the carousel.
	carouselObj.unlock();																	// write all changes to the DOM.

  //if(!ani){
  //  $(".jcarousel-clip .node-inner").animate({"opacity": 0}, 500);
  //}	
	
	//setTimeout(function(){
    carouselObj.scroll(first, false);											// scroll to the correct position without animating.
	  carouselObj.scroll(second, ani);											// Animate to the clicked position.  
  //}, animationTimeout);
	
	//if(!ani){
	  //setTimeout(function(){
	  //  $(".jcarousel-clip .node-inner").animate({"opacity": 1}, 500);
	  //}, 500);
	//}
	
}

function unbind_expandable_menus() {
  $(".carousel-menu-item-link").unbind("click");
}
function init_expandable_menus() {
  $(".carousel-menu-item-link").mouseover(function() {
    $(this).children("ul.menu").show();
  })
  .mouseout(function() {
    $(this).children("ul.menu").hide();
  });
		//
		// Removed because the links in the product section no longer need to slide in
		// showcase item. Functionality now takes you directly to a page.
		//
		//		$(".carousel-menu-item-link > a").click( function() {
		//    return false;
		//  });
		//		$("#node-1507 .carousel-item-links UL A").click(function() {
		//    var hash = this.href.replace(/^.*#/,'').concat();
		//    $.history.load(hash);
		//
		//    return false; //navigationalClick(this, carousel);
		//  });
}


/* A FEW TWEAKS */
function doTweaks(){
// Add extra classes for targeting an expanded pager ul
  
}
/* END TWEAKS */
